调用插件外部的自定义函数并传递参数

Call the custom function which outside plugin and pass parameter

本文关键字:参数 自定义函数 插件 外部 调用      更新时间:2023-10-05

我想尝试在插件外部调用一个函数,该函数由插件的"选项"传递。可以调用该函数,但我的代码无法传递插件中定义的参数。

如何将这些参数从内部传递到公共范围?


$(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');

在文档中指定参数仍然允许用户使用它们。