Question

When using the _trigger method in order to fire events I've hit a snag which I keep hitting but fail to properly grasp.

Basically, if there's more then one instance of my widget, the last widget to be instantiated on the same page takes precedence over all others.

I've learnt and successfully used $.extend to create an object unique to the instance but I'm stumped on how to approach the following problem:

How to I properly use the _trigger method so it's enable on a per instance basis.

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

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

Was it helpful?

Solution

You have an accidental global variable:

_this = this;

That means that both instances of the plugin put their this into the same (global) _this in the constructor. The result is that all the plugin instances use the this for the last one bound. You want this:

var _this = this;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top