【问题标题】:Call the custom function which outside plugin and pass parameter调用插件外部的自定义函数并传递参数
【发布时间】:2013-12-11 02:44:45
【问题描述】:

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

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


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

【问题讨论】:

    标签: javascript jquery function arguments


    【解决方案1】:

    只是改变:

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

    到:

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

    这将调用testingCall 并传入传递给afterDone 的原始参数列表。我为apply 的第一个参数传递了null,因为我不确定您想为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/

    但这可能会让人感到困惑,尤其是对于 JavaScript 新手而言。让用户知道(在文档中)您正在向 afterDone 预先提供两个参数可能更有意义,以便他们可以自行决定使用它们:

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

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

    虽然(据我所知)在以下行编辑任何内容都无法完成:

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

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

    【讨论】:

    • 谢谢。但是为了让插件的用户更简单,这可以通过在“settings.afterDone('para01','para02');”行编辑一些东西来完成吗? ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多