Reputation: 1771
I have started working with Backbone.
While learning Backbone, I got to know that the advantage of using .listenTo instead of .on is that listenTo allows "the object to keep track of the events".
I did not got what this sentence is trying to say. Well I can only see the difference between .on and .listenTo is about syntax.
Upvotes: 2
Views: 894
Reputation: 434685
Consider two calls:
this.model.on('change', this.some_method);
this.listenTo(this.model, 'change', this.some_method);
In the first case:
this.model
knows that someone is listening for 'change'
events but it doesn't know who.this
doesn't know what it is listening to unless you explicitly track what on
calls you've made.In the second case:
this.model
knows that someone is listening for 'change'
events but it doesn't know who.this
knows that it is listening to events from this.model
.So yes, the syntax is different but the main difference is who knows who is listening: with on
, only the thing being listened to knows that there is a listener; with listenTo
, the listener also knows what they're listening to.
The difference is important if you want to stop listening to events. If you're using on
then you have to maintain your own list of what you're listening to so that you can off
them; if you're using listenTo
then listenTo
keeps track of that and you can simply stopListening
.
For example, View#remove
looks like this:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
}
so you can call view.remove()
and it will automatically clean up any event bindings you have (as long as you used listenTo
) and the chance of zombie listeners is drastically reduced.
Upvotes: 5