Communicating via Events

Learn how to delete a contact using events in Marionette.

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:

Press + to interact
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:

Press + to interact
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);
}
}
...