Vladimir Zotov
Vladimir Zotov

Reputation: 621

Object assessible outside jQuery plugin

I have two jQuery plugins: The first one:

;(function($){

    function CbUploader(element,options){
        widget=this;
        .....
    }
    $.fn.cbUploader = function(options){
        new CbUploader(this,options);
        return this;
    }; 
})(jQuery);

And the second one:

;(function($){

    function CbGallery(element,options){
        widget=this;
        $('body').on('click',".thumbnail-upload",function(){
             console.log(widget)
        });
    $.fn.cbGallery = function(options){
        new CbGallery(this,options);
        return this;
    };

})(jQuery);

When I click on .thumbnail-upload div console.log returns CbUploader object instead CbGallery. Why plugin scope isolation doesn't work in my case?

Upvotes: 0

Views: 21

Answers (1)

eisbehr
eisbehr

Reputation: 12452

Don't register widget variable globally, use a local variable with var. Like you did, you use window.widget = this witch override each other then.

function CbGallery(element, options) {
    var widget = this;

    $('body').on('click', '.thumbnail-upload', function() {
        console.log(widget);
    });
}

And do the same in the CbUploader function too.

Upvotes: 1

Related Questions