user1324762
user1324762

Reputation: 805

jQuery $(this) inside function

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 );
  });
});

Upvotes: 2

Views: 14907

Answers (4)

Harmen
Harmen

Reputation: 22438

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 );
  });

Upvotes: 8

David Hellsing
David Hellsing

Reputation: 108490

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);
});

Upvotes: 1

James Kyburz
James Kyburz

Reputation: 14453

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 );
});

Upvotes: 0

David G
David G

Reputation: 96800

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

 // ...

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

Upvotes: 0

Related Questions