Avoidance var _this = this; when writing jQuery event handlers

Not a very important question, but here we go.

How to avoid using var _this = this in jQuery event handlers? that is, I do not like to do:

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

The following two methods are not perfect.

 $(el).click($.proxy(function (event) { //lost access to the correct dom element, ie 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 
+6
source share
3 answers

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

"This property will usually be equal to the value of the function."

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

+2
source

I'm not quite sure I understand you correctly, but if you want, this is a link to the function that you used when creating the callback function, you could do it like this (although this does not mean that you are saving any kind of print) :

 $(el).click(function(parent) { return function() { // Use parent instead of _this } }(this)) 
+2
source

You cannot assign this both the object and the DOM element. My recommendation is to assign the object to a different variable than this .

The best way to access both the object and the DOM element would look something like this:

 $(el).click($.proxy(function (event) { // can reference DOM element with this ie $(this) // can reference your object with the variable myObject // ie $(this).val(myObject.data); }, myObject)); 

or maybe like this:

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

Using a variable other than this inside the click event handling function will also make your code clearer, as most people would expect this refer to a DOM element and has nothing to do with your custom object.

0
source

Source: https://habr.com/ru/post/899133/


All Articles