Listening for Events with Backbone Views

This is something that I’ve learned before, and I think I even have it in my notes from when we first learned this, but on Friday, we used two ways to listen for events in Backbone, and I wanted to really solidify this in my mind so I stop getting confused!

One kind of events we can listen for are browser events like click, hover, or focus. The way to ‘listen’ for these kinds of events in a Backbone View is to use an events property in the Backbone View, like so:

events: { '.delete click': 'removeComment' }

The property of the events object is what event we are looking for. In this example, we are listening for a click action on something with the class ‘delete’. The value of the property is what View property should be called when the event occurs.

The other kind of events we can listen for are Backbone events. These are events like ‘add’, ‘remove’, or ‘change’ in Views, Models, or Collections that can trigger further actions. They are set via the listenTo(); function in the initialize property in the View, like so:

initialize: function (options) { this.listenTo(this.collection, 'add', this.addCommentToWall); }

Here, we are saying that we want this instance of the Backbone View to listen to the instance of a Backbone Collection that has been assigned to it. It is listening for something to be added. When something is added, we want to call addCommentToWall, which is a property of the same instance of the Backbone View.

Recap: I have learned two ways to listen for events using Backbone.js. The events property is for listening for browser events. The listenTo() function in the initialize property is for listening for changes in backbone objects.

Leave a Reply

Your email address will not be published. Required fields are marked *