【问题标题】:Unable to use apply() to call Backbone trigger() method无法使用 apply() 调用 Backbone trigger() 方法
【发布时间】:2014-02-11 04:46:44
【问题描述】:

我正在尝试创建一个通用辅助函数,该函数可用于触发 Backbone Marionette 模块上的事件。您可以将带有“模块”、“事件”和“参数(可选)”键的对象或此类对象的数组传递给它。如果您将具有moduleevent 属性的单个对象传递给它,它将为该模块调用该事件。如果您还向它传递一个 params 属性,它是一个数组,它也会传递它。这是我目前所拥有的:

/**
 * Triggers events for given module(s)
 *
 * @param {object|array} options - Either a single object with 'module', 'event' and 'params (optional)' keys, or an array of such objects
 */
var triggerModuleEvents = function (options) {
    require(['webapp'], function (WebApp) {
        var i, module, event, params;

        if (options instanceof Array) {
            for (i = options.length; i--;) {
                module = WebApp.module(options[i].module);
                event = options[i].event;
                params = undefined;
                params = options[i].params;

                if (typeof params === 'undefined') {
                    module.trigger(event);
                } else if (params instanceof Array) {
                    params.unshift(event);
                    module.trigger.apply(this, params);
                } else {
                    throw new TypeError('Params must be an array of parameters to pass with the event.');
                }
            }
        } else if (typeof options === 'object') {
            module = WebApp.module(options.module);
            event = options.event;
            module.trigger(event);
            params = undefined;
            params = options[i].params;

            if (typeof params === 'undefined') {
                module.trigger(event);
            } else if (params instanceof Array) {
                params.unshift(event);
                module.trigger.apply(this, params);
            } else {
                throw new TypeError('Params must be an array of parameters to pass with the event.');
            }
        } else {
            throw new TypeError("Argument must be an object with 'module' and 'event' keys, or an array of such objects.");
        }
    });
}

所以,我遇到的问题是触发方法 (module.trigger(event)) 工作正常,但我无法传递 params 数组。因为我不知道可能有多少参数,所以我需要使用apply(),但是有一些语法问题或者我遗漏了一些东西,只是看不到。具体来说,这条线似乎没有做任何事情 - module.trigger.apply(this, params) 这是一个应该如何调用助手的示例:

Utils.triggerModuleEvents([
    {
        module: 'Foo',
        event: 'some:event:namespace',
        params: [ null, true ]
    },
    {
        module: 'Bar',
        event: 'another:event:namespace'
    }
]);

【问题讨论】:

    标签: javascript backbone.js marionette backbone-events


    【解决方案1】:

    问题在于使用this 关键字,因为我看到您要做的只是更改参数顺序而不是将范围上下文更改为this,因此您应该将其更改为:

    module.trigger.apply(module, params);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 2012-11-12
      • 2013-04-15
      • 1970-01-01
      • 2014-07-31
      • 2015-10-28
      • 2019-01-17
      相关资源
      最近更新 更多