jQuery Widget Factory _trigger Instance

1.6k views Asked by At

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/

1

There are 1 answers

0
mu is too short On BEST ANSWER

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/