by drewda · 13y ago · 0 comments
`listenTo` and `stopListening` just give you an inverted (and often easier) way to manage the references ... so that you can remove all of the references from the "other" side. For example:
view.listenTo(model, 'change', view.renderChange);
view.listenTo(collection, 'add', view.addItem);
view.listenTo(Backbone, 'initialLoad', view.reinit);
# ... and then, when you want to get rid of the view:
view.remove();
# Calls view.stopListening(), removing *all* of the
# events from "view" bound on all of those different objects.
Note that none of this is necessary if you throw away both sides of the bound event at the same time -- those will still be GC'd as usual. Also, this isn't just for Views. The methods are available on anything that mixes in Backbone.Events.> Tell an object to listen to a particular event on an other object. The advantage of using this form, intead of other.on(event, callback), is that listenTo allows the object to keep track of the events, and they can be removed all at once later on.
I had to read this a few times and the given example to see that the convenience comes from tracking events on the listening object side.
Using "object" and "other" for the object variable names makes it a little confusing. I didn't realize the bolded "object" meant the listener object, as opposed to the object being listened to.
> listenTo object.listenTo(other, event, callback)
I think changing the naming to be more specific and updating the description names could help out.
listenTo observingObject.listenTo(actingObject, event, callback)
One caveat is that this breaks consistency with the other examples in this section (i.e. object.once(...) object.trigger(...)).This doesn't account for any child-views, or views that don't use .remove(), so you'll need to make sure those are taken care of when a view is destroyed. But in most cases, the garbage collection issues that have been seen relating to views & events are taken care of.