I had these lines in my javascript file and it was working fine.
handleInput = function(e) {
var $this = $(this),
id = $this.attr("id");
alert(id);
}
....
something.bind("keyup", handleInput);
Then I decided to delay the input function and added following lines:
handleDelayedInput = function(e) {
setTimeout(handleInput(e), 50);
}
.....
something.bind("keyup", handleDelayedInput);
But now alert(id); says undefined, because I think I couldn’t pass the this to that function.
Am I right? How can I fix? Is there any better way to do that?
When jQuery calls the event handler it sets the context of the handler function. This isn’t the case when handleInput is called in your second piece of code, so
thisis set to the default valuewindow.You can use
applyorcallto set the context:The difference between the two is that
applytakes an array of arguments while you can pass the arguments tocallone by one:func.apply(context, arg1, arg2).So your full code would be:
Note that, since we’re using setTimout we need to find a way to pass the element to the timeout handler function. Also, in your code you’re using the return value of
handleInput(e)as the handler function – rather thanhandleInput.I agree with Mike though, if you wrote handleInput yourself and you can modify it there’s not point in using
thisinstead of just passing the argument. If you still want to use handleInput as a direct handler somewhere else it would make sense to keep it the way you have it.