【问题标题】:jQuery $.myPlugin() style pluginjQuery $.myPlugin() 样式插件
【发布时间】:2013-01-09 12:13:13
【问题描述】:

我正在使用以下模式编写一个 jquery 插件(因为我不想做 $("#element").myPlugin(),我没有对特定元素做任何事情......反正......

$.extend({
    myPlugin: function(){
        //some cool stuff
    }
});

但我还需要其他插件改变我的插件行为的方法,我尝试执行以下操作,但遇到了一个奇怪的错误...

$.extend({
    myPluginStyles: {
        someStuff: {},
        moreStuff: {},
    }
});

$.extend({
    myPlugin: function(options) {
        this.style = $.myPluginStyles[options.style]; //options.style will contain either "someStuff" or "moreStuf"
    }
})

现在,其他插件可以在 myPluginStyles 对象中添加新的“样式”..至少是这样:

$.myPluginStyles.newStyle = {};

现在你可以做 $.myPlugin({style: 'newStyle'});

但我收到以下错误:

Uncaught TypeError: Property 'style' of object function (e,t){return new v.fn.init(e,t,n)} is not a function 

提前致谢。

【问题讨论】:

    标签: jquery design-patterns plugins


    【解决方案1】:

    也许这就是您要找的东西?这样,插件就有一个对象'styles',可以注册(使用registerStyles)和使用(使用this.styles[name])的东西。

    $.fn.extend({
        myPlugin: {
            styles : {}, //define the style object
            registerStyles : function(name, style) {
                //register name and style in the plugin's styles object
                this.styles[name] = style;
            },
            doStuff: function(name){
                //test by alerting the first value in the styles object
                alert(this.styles[name])
            }
        }
    });
    

    用法:

    $.fn.myPlugin.registerStyles('myStyle', 'test'); //set style
    
    $('#my_element').myPlugin.doStuff('myStyle'); //do stuff (in this case echo-ing the style)
    
    // or $.fn.myPlugin.doStuff('myStyle'); if you your function is not designed to use an element
    

    我不知道这是否是最佳做法,但我会这样做。

    See this fiddle 用于演示

    【讨论】:

    • 酷,我想出了如何去做,我基本上是在创建 2 个相互交织的插件。一种使用 $.myPlugin(),另一种可以使用 $('#element').myPlugin()。我很感激,谢谢:)
    【解决方案2】:

    $.extend 的样式适用于使用此模式的新插件 $(element).yourFunction.

    所以,你不想创建插件,你只想为 jQuery 添加功能。 那么你需要做什么:

    $.myPlugin=function () {alert('yourfunction') };
    $.myPluginSeries={someStuff:'', someStuff2: ''};
    

    我希望我清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多