如何使用 jquery 扩展插件中的 public 方法?
How can I extend the public methods in a plugin with jquery?
如何使用 jquery 扩展插件中的 public 方法?
$.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()}
可能吗?
您只需稍微修改代码即可将对象传递给插件,例如
$.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
块所做的是,它检查提供的参数是否是对象,然后使用 [=13= 以 属性 的名称将方法添加到 PluginApi
]循环。
你可以打电话给$(this).myPluginName(extensionMethods);
如何使用 jquery 扩展插件中的 public 方法?
$.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()}
可能吗?
您只需稍微修改代码即可将对象传递给插件,例如
$.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
块所做的是,它检查提供的参数是否是对象,然后使用 [=13= 以 属性 的名称将方法添加到 PluginApi
]循环。
你可以打电话给$(this).myPluginName(extensionMethods);