Benny Neugebauer Benny Neugebauer - 3 months ago 17
jQuery Question

Get instance / reference from jQuery prototype function ($.fn)

I wrote a jQuery plugin that uses a prototype.

Example:

function MyWidgetConstructor(element) {

this.id = 'test';
this.$element = $(element);
this.$element.data('instance', this);

}

MyWidgetConstructor.prototype.sayHello = function() {
alert('Hello, my ID is: ' + this.id);
}

$.fn.myWidget= function() {
return this.each(function() {
new MyWidgetConstructor(this);
});
};


I use the data attribute to save a reference to the widget. This way I can call the prototype methods with instance variables as follows:

jQuery('#myInstance').myWidget();
jQuery('#myInstance').data('instance').test();


However, that is not always working. Is there another way to get to the reference (maybe without the use of a data attribute)?

Answer

I have found another approach! One can use a global instance array to manage the different instances.

Example:

(function ($) {

    window.InstanceCollection = window.InstanceCollection || {};

    $.fn.myWidget = function () {
        return this.each(function () {
            new MyWidgetConstructor(this);
        });
    };       

    function MyWidgetConstructor(element) {
        this.id = 'test';
        window.InstanceCollection[this.id] = this;
    }

    MyWidgetConstructor.prototype.sayHello = function () {
        alert('Hello, my ID is: ' + this.id);
    }

})(jQuery)

jQuery(function ($) {
    $('#myInstance').myWidget();
    window.InstanceCollection['test'].sayHello();
})