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

Brendan Delumpa picture Brendan Delumpa · Dec 23, 2011 · Viewed 40.3k times · Source

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.

Answer

Paul picture Paul · Dec 23, 2011

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