I’m looking for a way to implement a custom “enterKey” event for jQuery:
$('selector').enterKey(function(){
alert( $(this).val() ) // doesn't work
});
i have done something similar to https://stackoverflow.com/a/5689145/1123630
and it works with one exception: i cannot access $(this) from within my anonymous function
Simplified version of what i want:
$.fn.test = function( ev ) {
ev();
}
$('#val').test( function(){
alert( $(this).val() ); // works well with static text,
//but not with "this" pointer
});
Any help would be apreciated
The way you call
ev,thiswill refer to the global object (windowin browsers).MDN has a nice summary about
this.You have to explicitly set
this, usingcall[MDN] orapply[MDN], or just pass the callback toeach[docs]:By using
each, you make sure thatthisinside the callback you pass only refers to one DOM element, just like other callbacks work, like the one you pass to.click().Otherwise, inside a plugin method,
thisrefers to all selected elements. So this would be wrong (or at least different from typical jQuery callbacks):On the other side, this would be OK as well, but is unnecessarily verbose:
Though you have to do this if you wanted to pass custom arguments to your callback (
ev), otherwiseevreceives the same arguments as theeachcallback.