如何使用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()}
有可能吗?
答案 0 :(得分: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
块的作用是,它检查提供的参数是否为对象,然后使用PluginApi
循环将属性名称的方法添加到for...in
。
您可以拨打$(this).myPluginName(extensionMethods);