简体   繁体   中英

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

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:

{
    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.

Yes, that is possible with Backbone.

You can use the Events module to allow an object the ability to bind and trigger custom named 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

_.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"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM