mritz_p
mritz_p

Reputation: 3098

How to proxy an anonymous function so that both "this" keywords are available?

I would like to use the jQuery.proxy method to provide a context for an anonymous function. At the same time I would like the context of the proxied original function to be available.

Consider this example:

example.find("li").each($.proxy(function(i) {
    var context = this; // Great! This gives me the context of the function call as expected.
    var $li = '???'; // How can I access the jQuery element of the <li>? $(this) obviously won't do.
}, this));

How would I access the iterated <li> elements here?

Upvotes: 0

Views: 77

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

I use the following method:

var self = this;
example.find("li").each(function() {
    var $li = $(this); // this is the <li>
    self.someMethod(); // self is the context
});

Upvotes: 0

Adam
Adam

Reputation: 6733

Use the second parameter to the .eachcallback

example.find("li").each($.proxy(function(i, el) {
    var context = this; // Great! This gives me the context of the function call as expected.
    var $li = $(el);
}, this));

See documentation for .each()

Upvotes: 3

Related Questions