1

I'm trying to store the value of an input (in an array) each time it is updated. I have multiple inputs with the structure:

<input class="inf" key="213" type="CUSTOM" value="val">

Then I had this working function:

$('.inf').on('keyup', function () {
    clearTimeout(temp2);
    temp2= setTimeout(updateValues.call(this), doneTypingInterval);
});

But the setTimeout doesn't work, so I used this solution and changed it to:

temp2= setTimeout(function () {updateValues.call(this);}, doneTypingInterval);

Now, setTimeout is working but, when updateValues is reached, all 3 variables are "undefined".

updateValues function:

var updateValues= function(){
            
 key=$(this).attr("key");
 type=$(this).attr("type");
 value=this.value;
                
    upd={
        "name" : '"'+key+'"',
        "type" : '"'+type+'"',
        "value" : '"'+value+'"'
    };
 nw = nw.concat(upd);
 console.log(nw);
};

The problem is that the this object in updateValues is what I passed with the call. Any suggestions?

Exelian
  • 5,364
  • 1
  • 28
  • 46
Fels
  • 13
  • 2

1 Answers1

1

The direct answer to your problem is to use .bind() instead of .call():

temp2 = setTimeout(updateValues.bind(this), doneTypingInterval);

or use the arrow function:

temp2 = setTimeout(() => { updateValues.call(this); }, doneTypingInterval);

More on how this works can be found in this great answer

Sebastian Kaczmarek
  • 7,135
  • 4
  • 17
  • 36