r5sgbq
Last Updated: February 25, 2016
·
2.363K
· dperrymorrow
37b092a324da25d53fd63d780692b174

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));
  }
}
Say Thanks
Respond

3 Responses
Add your response

1940

Thanks for sharing !
Just missing a close bracket after line:
$('a').click( $.proxy(this, 'clickFunction');

over 1 year ago ·
1944
37b092a324da25d53fd63d780692b174

@blackblist My bad, fixed thanks for reading!

over 1 year ago ·
2012
2017 cs

great tip, thanks

over 1 year ago ·