我怎么称呼功能?

时间:2014-07-01 13:42:54

标签: javascript jquery

假设点击按钮后 - 我们发送请求。我有jquery插件,结构如下:

(function($){

    $.myPlugin = {
        defaults: {}
    };

    $.fn.extend({
        /**
         * Initializes the plugin
         */
        myPlugin: function(settings)
        {
            return this.each(function() {

                settings = $.extend({}, $.myPlugin.defaults, settings);
                $.data(this, "myPlugin", settings);

                var self = this;

                $('#button', self).on('click', function () {
                    functionTwo.call(this);
                });
            });
        }
    });

    function functionOne()
    {
        alert(1);
    }

    function functionThree()
    {
        alert(3);
    }

    function functionTwo(self)
    {
        $.ajax({
            url: '/some_url',
            type: 'GET',
            success: function (response) {

                // Here I need to call function depends on response.funcName.
                // Where funcName can be functionThree, functionOne, etc.
                // I try something like that: window[funcName], etc. But it was
                // not successfully.
            } 
        });
    }
})(jQuery);

这里的函数在ajax响应后我需要调用函数依赖于response.funcName。其中response.funcName可以是functionThree,functionOne等。我尝试类似的东西:windowfuncName等。但它没有成功。

我不明白这个函数(functionThree,functionOne等)的声明在哪里,在什么范围内?我怎样才能动态调用它?

1 个答案:

答案 0 :(得分:2)

尝试将函数放在对象中,以便使用括号语法引用它们:

(function($){
    var functions = {
        functionOne: function() {
            alert(1);
        },
        functionThree: function() {
            alert(3);
        },
        functionTwo: function(self) {
            $.ajax({
                url: '/some_url',
                type: 'GET',
                success: function (response) {
                    functions[response.funcName]();
                }
            });
        }
    }

    $.myPlugin = {
        defaults: {}
    };

    $.fn.extend({
        /**
         * Initializes the plugin
         */
        myPlugin: function(settings)
        {
            return this.each(function() {

                settings = $.extend({}, $.myPlugin.defaults, settings);
                $.data(this, "myPlugin", settings);

                var self = this;

                $('#button', self).on('click', function () {
                    functions.functionTwo.call(this);
                });
            });
        }
    });
})(jQuery);