开发者

Jquery plugin scope question (closures)

I'm trying to make a plugin and am running into some problems:

(function($){
    var users = {};

    $.fn.plugin = functio开发者_JS百科n(){
        //blah, but alters users
    }
    $.fn.utility_function = function(){
        // uses users
    }
});

What's happening is that when I run two instances of this plugin, "users" ends up having the same value for each instance of the plugin. How do I make them unique?


That's completely normal, because your users object lives outside the scope of your plugins.

I suggest you store the value as part of the data() jquery method attached to your dom element affected by the plugin

see this article.


If you'd like unique objects, you can make a deep copy of an object with jquery's built in extend method.

In your case, you'd do:

(function($){
    var users = {};

    $.fn.plugin = function(){
        var myUsers = $.extend({}, users);
        //blah, but alters users
        // BUT should now use myUsers instead
    }
    $.fn.utility_function = function(){
        // uses users
    }
});

But I'm not sure you'd want unique copies of the users object, since they probably are a single set that probably only changes globally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜