Search⌘ K

Communicating via Events

Explore how to use events, event bubbling, and the trigger method in Marionette.js to manage interactions in your applications. Understand how child view events bubble up to parent views and how to handle them efficiently.

Triggering an event for deleting a contact

Let’s trigger an event indicating a contact should be deleted instead of deleting it directly in the view:

Node.js
List.Contact = Marionette.ItemView.extend({
// tagName and template attributes
events: {
"click": "highlightName",
"click button.js-delete": "deleteClicked"
},
// highlightName handler
deleteClicked: function(e){
e.stopPropagation();
this.trigger("contact:delete", this.model);
}
});

The view’s trigger method in line 13 is given an event name to trigger and an argument to pass
on. Next, we need to process this event within our controller:

Node.js
List.Controller = {
listContacts: function(){
var contacts = ContactManager.request("contact:entities");
var contactsListView = new List.Contacts({
collection: contacts
});
contactsListView.on("childview:contact:delete", function(childView, model){
contacts.remove(model);
});
ContactManager.regions.main.show(contactsListView);
}
}


Once again, it’s important to remember scopes when dealing with events: ...