简体   繁体   English

这是有效的jQuery插件模式吗?

[英]Is this a valid jQuery plugin pattern?

(function( $ ){  
    MY_SINGLETON_OBJ = MY_SINGLETON_OBJ || (function () { // initialize the singleton using an immediate anonymous function which returns an object
        // init here (only happens once even if this plugin is included multiple times)
        console.log("Initialized");
        return {
            version: "0.1"
            // return values that are to be accessible from the singleton
        };
    })();
    $.fn.MyJqueryObjectMethod = function (a, b, c) {
        // perform tasks
        return this; // maintain chainability
    };
})(jQuery);

The singleton is polluting the global namespace. 单例正在污染全局名称空间。 Is there a better way to define it? 有没有更好的方法来定义它?

That looks to me like it would work, though I think you should at least declare your singleton globally rather than use an implicit definition. 在我看来,这似乎是可行的,尽管我认为您至少应该全局声明您的单身人士,而不是使用隐式定义。

You don't have to be that tricky. 您不必那么棘手。 You can just as easily do this which I think it a bit more readable and obvious: 您可以轻松地做到这一点,我认为它更具可读性和明显性:

// explicit global definition
var MY_SINGLETON_OBJ;

(function( $ ){  
    if (!MY_SINGLETON_OBJ) {
        // initalize the singleton here
        MY_SINGLETON_OBJ = {};
        MY_SINGLETON_OBJ.prop1 = 1;
    }
    $.fn.MyJqueryObjectMethod = function (a, b, c) {
        // perform tasks
        return this; // maintain chainability
    };
})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM