Last Updated: February 25, 2016
·
43.96K
· thurloat

Using Backbone's new `listenTo`

Backbone 0.9.9 has included a new mechanism for managing event bindings on objects so that you don't end up with objects that are immune to garbage collection.

It's simple to convert your views to use the new listenTo method. For every instance of:

// model
model.on("change", changeCallback);

// collection
collection.on("reset", resetCallback);

change it to:

// model
this.listenTo(model, "change", changeCallback);

// collection
this.listenTo(collection, "reset", resetCallback);

And with that change, your view becomes aware of all of the object event bindings and when the view is destroyed, it will automatically tear down those events for you in View.remove().

5 Responses
Add your response

Nice! I've been dealing with zombie views for quite some time - even prototyping close.. 've tried everything i can think of and regardless, sometimes, an event will trigger multiple times and this looks like the fix. Very Nice!

over 1 year ago ·

@andrewjhart if you want to get even more awesome with your zombie views, check out my blog post going even deeper: http://thurloat.com/2012/12/13/backone-listening-helps-memory

over 1 year ago ·

Thanks Adam!

Also, you can bind to multiple events by separating them with a space like so:

this.listenTo(ContactsCollection, 'add remove', this.render)
over 1 year ago ·

furthermore, you can simply listen to the change event similar to the model:

this.listenTo( myView.collection, "change", this.onViewCollectionChangeHandler ); 

On the handler, you will receive the updated model...

onViewCollectionChangeHandler: function(model) {
over 1 year ago ·

this.listenTo( this.collection, 'add', this.renderBook );

renderBook: function( item ) {
console.log("this is renderBook");
var bookView = new app.BookView({
model: item
});
this.$el.append( bookView.render().el );
},

events:{
'click #add':'addBook'
},
addBook: function( e ) {
console.log("This is event mathod");
e.preventDefault();
var formData = {};
$( '#addBook div' ).children( 'input' ).each( function( i, el ) {
if( $( el ).val() != '' ){
formData[ el.id ] = $( el ).val();
}
});
this.collection.add( new app.Book( formData ) );
console.log(JSON.stringify(formData));
},

this code is not working......

over 1 year ago ·