Using jQuery $.proxy
Hate spagetti code? Functions nested like 3 or 4 levels deep?
Me too. The best way I have found to avoid overly nested code is to use jQuery's $.proxy method to keep things as flat as possible, and on the class or module level.
Consider this code...
MyClass = function () {
this.setupEvents = function () {
$('a').click(function (event) {
console.log($(event.target));
});
}
}
And the alternative using jQuery's $.proxy method
MyClass = function () {
this.setupEvents = function () {
$('a').click( $.proxy(this, 'clickFunction'));
}
this.clickFunction = function (event) {
console.log($(event.target));
}
}Written by David Morrow
Related protips
3 Responses
Thanks for sharing !
Just missing a close bracket after line:
$('a').click( $.proxy(this, 'clickFunction');
over 1 year ago
·
@blackblist My bad, fixed thanks for reading!
over 1 year ago
·
great tip, thanks
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#