Last Updated: February 25, 2016
·
3.678K
· dperrymorrow

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));
  }
}

3 Responses
Add your response

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 ·