Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding var _this = this; when writing jQuery event handlers

Not a very important question, but here we go..

How do you avoid using var _this = this in jQuery event handlers? i.e. I don't like doing:

var _this = this;
$(el).click(function (event) {
  //use _this to access the object and $(this) to access dom element
});

The following 2 ways are not ideal

$(el).click($.proxy(function (event) {
  //lost access to the correct dom element, i.e. event.target is not good enough (see http://jsfiddle.net/ne3n3/1/)
}, this));

$(el).click({_this: this}, function (event) {
  //have access to $(this) and event.data._this, but it seems too verbose
})

Ideally I would like to do something like

$(el).click(function (event) {
  this.method(); // this is accessing the object
  event.realTarget; // this is accessing the dom element
}, this); // <= notice this
like image 255
Karolis Avatar asked Oct 12 '11 14:10

Karolis


2 Answers

http://api.jquery.com/event.currentTarget/ says:

"This property will typically be equal to the this of the function."

http://jsfiddle.net/ne3n3/2/

like image 122
biziclop Avatar answered Oct 16 '22 21:10

biziclop


I'm not entirely sure I understand you right, but if what you want is a reference to the function you were in when creating the callback function you could do it like this (although it's not exactly saving you any typing):

$(el).click(function(parent) {
    return function() {
        // Use parent instead of _this
    }
}(this))
like image 20
Thor84no Avatar answered Oct 16 '22 22:10

Thor84no