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.
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.
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.
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.
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"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With