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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#