调用插件外部的自定义函数并传递参数
Call the custom function which outside plugin and pass parameter
我想尝试在插件外部调用一个函数,该函数由插件的"选项"传递。可以调用该函数,但我的代码无法传递插件中定义的参数。
如何将这些参数从内部传递到公共范围?
$(document).myPlugin({
afterDone : function(){testingCall()}
});
function testingCall(){
alert(arguments[0]);
alert(arguments[1]);
}
(function($){
var MyPlugin = function(element, options){
var settings = $.extend({}, $.fn.myPlugin, options||{});
/* ------ Do somthing, whatever -----*/
//call the custom function here
settings.afterDone('para01','para02');
};
$.fn.myPlugin = function(options){
return this.each(function(key, value){
new MyPlugin(this, options);
});
};
$.fn.myPlugin.defaults = {
afterDone : function(){}
};
})(jQuery);
只需更改:
$(document).myPlugin({
afterDone : function(){testingCall()}
});
至:
$(document).myPlugin({
afterDone: function () {
testingCall.apply(null, arguments);
}
});
这将调用testingCall
并传入传递给afterDone
的原始参数列表。我为apply
的第一个参数传递了null
,因为我不确定要为this
使用哪个上下文。
Fiddle:http://jsfiddle.net/TGG2J/
更新
如果插件的用户事先不知道默认情况下要向afterDone
添加哪些参数,并且他们希望将这些参数传递给testingCall
,则必须这样定义afterDone
:
$(document).myPlugin({
afterDone: function () {
var userArgs = ['user01', 'user02'],
i = 0;
for (i = 0; i < arguments.length; i += 1) {
// to make your arguments the first arguments, do this
userArgs.splice(0 + i, 0, arguments[i]);
// to make the user's arguments the first arguments, do this
//userArgs.push(arguments[i]);
}
testingCall.apply(null, userArgs);
}
});
Fiddle:http://jsfiddle.net/TGG2J/1/
但这可能会让人感到困惑,尤其是对新的JavaScripter来说。让用户知道(在文档中)您正在向afterDone
预先提供两个参数,以便他们可以自行使用它们,这可能更有意义:
$(document).myPlugin({
afterDone: function (p1, p2) {
testingCall(p1, p2, 'myArgs');
}
});
Fiddle:http://jsfiddle.net/TGG2J/2/
虽然(据我所知)在以下行编辑任何内容都做不到:
settings.afterDone('para01','para02');
在文档中指定参数仍然允许用户使用它们。
相关文章:
- 自定义函数中的光标位置
- Google Sheet自定义函数返回0
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- dalek回调或自定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 评估作为参数传递给 Google 电子表格中自定义函数的条件
- 具有自定义函数调用的 HTML 表单
- 使用 jQuery 对动态创建的元素调用自定义函数
- 从自定义函数返回promise
- extjs-使用传递的参数创建自定义函数
- 调用插件外部的自定义函数并传递参数
- 我对javascript中的一个自定义函数感到困惑,该函数将对象作为参数获取
- 在应用脚本中,如何在自定义函数中包含可选参数
- 如何使用参数创建JQuery自定义函数
- 为什么自定义函数在IE8中说无效参数
- 使用自定义函数作为另一个函数的参数
- 如何将函数作为参数传递给Javascript中的自定义函数
- 为谷歌工作表的自定义函数添加伪参数