2

I want to pass $(this) to function but I am not sure. There is one similar thread, but I still can not make it working. I hope somebody can help me.

$(document).ready(function() {
  var delay = (function(){
    var timer = 0;
    return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
    };
  })();

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }, 1000 );
  });
});
user1324762
  • 765
  • 4
  • 7
  • 24

4 Answers4

8

You should save a reference to this :

$('input').keyup(function() {
    var $this = $(this);
    delay(function(){
      alert($this.val());
    }, 1000 );
});

Another option is to re-bind this to the function:

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }.bind(this), 1000 );
  });
Luan Nico
  • 5,376
  • 2
  • 30
  • 60
Harmen
  • 22,092
  • 4
  • 54
  • 76
1

You would need to bring the context:

return function(callback, ms, context){
  clearTimeout (timer);
  timer = setTimeout(function() {
      callback.call(context);
   }, ms);
};

And then

delay(function() {
    alert($(this).val());
}, 1000, this );

But as others posted, saving the context in a local variable might be what you really want. Here is another way to do it:

$('input').keyup(function() {
  delay((function(self) {
    return function() {
      alert($(self).val());
    };
  }(this)), 1000);
});
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

Keep a reference to $(this) outside the function.

 // ...

    $('input').keyup(function() {
        var $this = $(this);
        delay(function() {
            alert( $this.val() );
        }, 1000)
    });
David G
  • 94,763
  • 41
  • 167
  • 253
0

this changed because of function scope change. You need to store the value using a closure.

If all you pass is the value you don't need $(this)

$('input').keyup(function() {
  var val = this.value;
  delay(function(){
    alert(val);
  }, 1000 );
});

Another way would be

$('input').keyup(function() {
  delay((function(val){
    return function() {
      alert(val);
    };
  }(this.value)), 1000 );
});
James Kyburz
  • 13,775
  • 1
  • 32
  • 33