【问题标题】:Jquery plugin allow multiple instancesjQuery插件允许多个实例
【发布时间】:2014-08-06 05:30:24
【问题描述】:

我正在使用 jQuery boilerplate template 作为我正在编写的插件。它基本上只是运行一个 ajax 调用并替换它运行的元素的内容。示例:

我的插件名称是'getContent'

$('.container').getContent({
    html : 'foo'
});

非常简化的插件版本,但是在模板的最底部有这样的:

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations

$.fn[pluginName] = function(options) {
    this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
    });

    // chain jQuery functions
    return this;
};

显然,它会检查 pluginName 是否已经绑定到元素。在这种情况下,当您稍后在同一页面实例中再次尝试执行此操作时,该插件不会运行。

解决我的问题的正确方法是从字面上删除 new Plugin 部分周围的 if 吗?

【问题讨论】:

    标签: javascript jquery jquery-plugins html5boilerplate boilerplate


    【解决方案1】:

    为了能够为多个实例运行插件,您需要为每个实例创建一个新的闭包,请尝试以下代码:

    function getContentFunc(elem,options){
        //things you want your plugin to do
    };
    
    $.fn[pluginName] = function(options) {
        if ($.data(this, "plugin_" + pluginName)) return;
        return $(this).each(function() {
            getContentFunc(this,options);
            $.data(this, "plugin_" + pluginName);
        });
    };
    

    看一个很简单的插件,用同样的方法完成HERE

    【讨论】:

    • 抱歉,这不起作用,如果我将控制台日志添加到您的缩短功能中,它只会触发一次。
    • 当然它会触发一次,因为我们在代码中只有一个p 标签,复制相同的p 标签并添加console.log() 并看到它被触发了两次!跨度>
    • 如果我想在同一个 p 标签上运行它怎么办?
    • 对于简短的示例,这样做没有意义,但如果你想做这样的事情,你必须删除 if$.data(this, "plugin_" + pluginName);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多