Javascript Backbone.js - 使用触发器触发事件​​并传递数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8620160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:46:09  来源:igfitidea点击:

Backbone.js - using trigger to trigger event and pass data

javascriptbackbone.jsbackbone-events

提问by Brendan Delumpa

I'm writing a tab menu component using backbone.js as an MVC framework. When a user clicks on a tab, the component will switch tabs (internal operation), but then I would like listeners of the component to respond to the action associated with the event. The idea behind this is that I'm abstracting the various clicks into specific actions. For instance, the model for each tab is a hash with the following structure:

我正在使用backbone.js 作为MVC 框架编写选项卡菜单组件。当用户单击选项卡时,组件将切换选项卡(内部操作),但随后我希望组件的侦听器响应与事件关联的操作。这背后的想法是我将各种点击抽象为特定的动作。例如,每个选项卡的模型是具有以下结构的哈希:

{
    label : <string>,
    actionCommand : "save",
    tabClass : <string>
}

The event that will be triggered will be called "action," so listeners will respond to "action" but will then forward the specific command. For instance:

将被触发的事件将被称为“动作”,因此侦听器将响应“动作”但随后将转发特定命令。例如:

this.trigger("action", {actionCommand: "save"});

The listener in turn would handle the event similarly to the following:

侦听器将依次处理与以下类似的事件:

handleAction : function(event) {
  if (event.actionCommand == "save") {
    ...do something...
  }

}

}

Is this possible? I couldn't glean this from the documentation. Thanks in advance for any insight you can offer.

这可能吗?我无法从文档中收集到这一点。预先感谢您提供的任何见解。

回答by Paul

Yes, that is possible with Backbone.

是的,这可以通过 Backbone 实现。

You can use the Events module to allow an object the ability to bind and trigger custom named events.

您可以使用 Events 模块来允许对象绑定和触发自定义命名事件。

In your case, you would want to add the Events module to your menu component object. If this object is a Backbone Model, then it already has the Events module. If not, then you can add it with the following code

在您的情况下,您可能希望将 Events 模块添加到菜单组件对象中。如果这个对象是一个主干模型,那么它已经有事件模块。如果没有,那么您可以使用以下代码添加它

_.extend(MenuComponent, Backbone.Events);

Then your listeners can subscribe like this

然后你的听众可以像这样订阅

MenuComponent.bind("action", this.handleAction, this);

And you can trigger the event like you already mentioned

你可以像你已经提到的那样触发事件

this.trigger("action", {actionCommand: "save"});