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

时间:2013-11-26 05:04:28

标签: javascript jquery function arguments

我想尝试在我的插件之外调用一个函数,该函数通过插件的“选​​项”传递。可以调用该函数,但我的代码无法传递我的插件中定义的参数。

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


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

1 个答案:

答案 0 :(得分:0)

只需改变:

$(document).myPlugin({
    afterDone : function(){testingCall()}
});

为:

$(document).myPlugin({
    afterDone: function () {
        testingCall.apply(null, arguments);
    }
});

这将调用testingCall并传入传递给afterDone的原始参数列表。我通过null获取apply的第一个参数,因为我不确定您要将哪个上下文用于this

小提琴: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);
    }
});

小提琴:http://jsfiddle.net/TGG2J/1/

但这可能会令人困惑,特别是对于新的JavaScripters。让用户知道(在文档中)您预先向afterDone提供两个参数以便他们可以自行决定使用它们可能更有意义:

$(document).myPlugin({
    afterDone: function (p1, p2) {
        testingCall(p1, p2, 'myArgs');
    }
});

小提琴:http://jsfiddle.net/TGG2J/2/

虽然(据我所知)通过以下方式编辑任何内容都无法做到:

settings.afterDone('para01','para02');

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