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
http://api.jquery.com/event.currentTarget/ says:
"This property will typically be equal to the this of the function."
http://jsfiddle.net/ne3n3/2/
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With