Search code examples
jqueryobjectjquery-pluginschaining

jQuery get correct acces to plugin object in each function


Is it possible to get access to jQuery's plugin object in each-function?

var pluginName = 'pluginName',
    Plugin = function(elem){
        elem.add = function () {
            console.log('foo');
            return this;
        };
    };

$.fn[pluginName] = function () {

    // this works
    new Plugin(this);
    return this;

    // this doesn't!
    // return this.each(function(){
    //     new Plugin($(this));
    // });
};

var plugin = $('.foo').pluginName();
plugin.add();

Solution

  • The context when you go inside of a .each() is not the same context as outside. You can maintain the context with a variable like this:

    var _this = this;
    return this.each(function(){
         new Plugin($(_this));
    });