1

I have been looking into a neater, shorter, more simplified way of working with setting variables on the JS Controller dynamically.

At the moment I have seen a lot of people writing a lot of code or having separate handlers for each separate field to manage the keyup or keydown process.

So I wanted to think of an easier way of doing this to keep my controller a little cleaner.

1 Answer 1

4

I found a pretty nifty way of doing this very simple process, which I wanted to share:

HTML:

<lightning-input value={test} data-id="test" onkeyup={valueChange} onkeydown={valueChange} variant="label-hidden"></lightning-input>

JS:

@track test;

valueChange(event) {
    this[event.target.dataset.id] = event.target.value;
}

Doing this simplifies the way that you are setting a value in the JS Controller, I have seen a LOT of people using case of if/else to then decide where to assign values, depending on the "data id".

2
  • I thing you need to use this.somevar[event.target.dataset.id] = event.target.value; Commented Mar 13, 2020 at 8:55
  • 1
    No the idea of it is you don't need to hardcode "somevar", you can access all variables with the this keyword, if you console.log(this); you can see all of the variables that are in your JS Controller
    – Tim
    Commented Mar 14, 2020 at 13:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .