JQuery Widget Factory _trigger Instance

When using the _trigger method to fire events, I fell into a trap that I continue to beat, but I can’t understand correctly.

Basically, if there is more than one instance of my widget, the last widget created on one page takes precedence over all others.

I recognized and successfully used $ .extend to create an object unique to the instance, but I am puzzled by how to approach the following problem:

How to properly use the _trigger method so that it is included for each instance.

(function($) { $.widget("a07.BearCal", { options: { }, _create: function() { _this = this; this.element.click(function() { _this._trigger("testTrig"); }); }, }); })(jQuery); // Instantiate widget on .full $('.full').BearCal({ testTrig: function() { console.log("testTrig event: full"); } }); // Instantiate widget on .mini $('.mini').BearCal({ testTrig: function() { console.log("testTrig event: mini"); } }); 

Example here: http://jsfiddle.net/NrKVP/13/

+4
source share
1 answer

You have a random global variable:

 _this = this; 

This means that both instances of the plugin put them this in the same (global) _this in the constructor. As a result, all instances of the plugin use this for their last binding. Do you want this:

 var _this = this; 

Demo: http://jsfiddle.net/ambiguous/9NQNz/

+6
source

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


All Articles