Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 996
Brendan Delumpa Avatar asked Dec 23 '11 20:12

Brendan Delumpa


People also ask

How do I trigger an event in Backbone JS?

js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it. Parameter Values: event: It is used to bind an object with an event.

Is Backbone JS still relevant?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Which function has to be used when you want to trigger the event only once before being removed?

js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.


1 Answers

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"});
like image 61
Paul Avatar answered Sep 18 '22 04:09

Paul