【问题标题】:How can I extend the public methods in a plugin with jquery?如何使用 jquery 扩展插件中的公共方法?
【发布时间】:2015-01-11 12:27:51
【问题描述】:

如何使用 jquery 扩展插件中的公共方法?

$.fn.myPluginName = function(PublicOptions) {

    // Remember the root assigned object.
    var Root = this;

    // Set private defaults.
    var Defaults = {
        param1:       'param1',
        param2:       'param2',
        onSuccess:    function(){}
    };

    // Do a deep copy of the options - http://goo.gl/gOSSrg
    var Options = $.extend(true, {}, Defaults, PublicOptions);

    // Private debug function.
    function log(msg) {
        console.debug(msg);
    }

    // Define the public api and its public methods.
    var PublicApi = {

        method1 : function (PublicOptions) {

            return "extended method 1";
        },
        method2 : function (PublicOptions) {

            return "extended method 2";
        }
    };

    // Return the PublicApi object.
    return PublicApi;
};

我想把它们放在var PublicApi = {}里面的扩展方法

var extensionMethods = {

   method3: function(){
       return "extended method 3";
   },

   method4: function(){
       return "extended method 4";
   }
};

目前,对于console.log($(this).myPluginName());

Object {method1=function(), method2=function()}

但如果我可以将方法扩展到,那将是理想的,

Object {method1=function(), method2=function(), method3=function(), method3=function()}

有可能吗?

【问题讨论】:

  • 是的,只需将method3method4 添加为PublicApi 的属性即可。

标签: jquery jquery-plugins jquery-1.9


【解决方案1】:

您可以将对象传递给插件,只需稍加修改代码即可

$.fn.myPluginName = function(extMethods){
    //(...) Some code here
    PluginApi = { ... }   // your default methods go here
    if(typeof extMethods == "object"){
       for(var key in extMethods)
           PluginApi[key] = extMethods[key];
    }
}

if 块所做的是,它检查提供的参数是否是一个对象,然后使用 for...in 循环将方法添加到 PluginApi 的属性名称。

你可以打电话给$(this).myPluginName(extensionMethods);

【讨论】:

  • @tealou 很高兴为您提供帮助 :)
  • 哦,k 来自哪里??
  • @tealou 抱歉.. 这是一个错字,Alexander 已修正。现在检查。顺便感谢亚历克斯!
猜你喜欢
  • 2013-08-08
  • 2011-11-23
  • 2012-08-17
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2014-10-10
  • 2011-04-25
相关资源
最近更新 更多