Reputation: 805
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
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
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
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
Reputation: 96800
Keep a reference to $(this)
outside the function.
// ...
$('input').keyup(function() {
var $this = $(this);
delay(function() {
alert( $this.val() );
}, 1000)
});
Upvotes: 0