Backbone series: Reacting to Events from Shared Collections
Jan 12, 2015
Continuing our Backbone.js series, we’re going to be looking at how we can react to events in one View, which have been triggered by another. Both Views will share the same Collection instance, which gives us our logical link.
In practice, what we actually want to do is render a bunch of users (from a Users Collection) on the page, and let the user delete them.
First, lets define out Models and Collections and create our Collection instance (fairly standard stuff):
Next we want to create our Users View, which will act as the container view for all the users on the page:
We can then create our User View, which will render out each User model and then attach the click handlers for deleting users:
Kick everything off by appending a new Users View to the DOM:
As you can see, we pass the Collection instance to the Users view. Then we pass each Model to a new User view, which means that when we destroy a certain model from a User View, the usersCollection knows about it and triggers a “remove” event.
If you’d like to play around with the code referenced above and see it all in action, check out the JSBin embed below (press the “Run with JS” button to reset the list after deletion).