Liviu Gelea
Liviu Gelea

Reputation: 361

Access $(this) from within anonymous jQuery function

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

Upvotes: 2

Views: 115

Answers (1)

Felix Kling
Felix Kling

Reputation: 816442

The way you call ev, this will refer to the global object (window in browsers). MDN has a nice summary about this.

You have to explicitly set this, using call [MDN] or apply [MDN], or just pass the callback to each [docs]:

$.fn.test = function( ev ) {
    return this.each(ev);
};

By using each, you make sure that this inside 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, this refers to all selected elements. So this would be wrong (or at least different from typical jQuery callbacks):

$.fn.test = function( ev ) {
    ev.call(this);
    return this;
};

On the other side, this would be OK as well, but is unnecessarily verbose:

$.fn.test = function( ev ) {
    return this.each(function() {
        ev.call(this);
    });
};

Though you have to do this if you wanted to pass custom arguments to your callback (ev), otherwise ev receives the same arguments as the each callback.

Upvotes: 7

Related Questions