DOM Events & Memory Management
Maps directly to jQuery event binding methods:
var SongView = Backbone.View.extend({
events: {
'click li': 'playSong',
'submit #myForm': 'handleSubmit'
},
render: function(){},
playSong: function(e) {
// handler
},
handleSubmit: function(e) {
// handler
}
})
Split on spaces [eventName selector]. Can do complex selector but not complex click handler. Instead of multiple event definitions, he suggest interface segregations.
Memory Management with Views
Normally GC is automatic (you cannot trigger it manually, but you can block it)
There are tools to monitor memory. Usually you don't have to think about it. Only if you have hundreds of views and never remove them from the DOM.
Views can be removed by calling
remove
. Buy if views have references to long-lived objects, they will remain in memory even after they are removed.An example when garbage collection will not happen:
var SongView = Backbone.View.extend({
initialize: function(options){
this.model.on('change', this.render, this);
}
});
song.remove(); // Not garbage collected because of event binding
From Backbone 1.1. you don't need to worry about this.You would needed to first call
this.model.off
to unbind the event listener.OR
You can use
this.listenTo(this.model, 'change', this.render, this)
instead and it will not block GC. listenTo
will keep an internal reference. when you call remove()
it will trigger .stopListening()
internally.So just use
listenTo
automatically!