When an ItemView is listening to a model other than its model (this.model), do I simply need to turn off listeners within the remove function? And set their reference to null? I wonder if the ItemView will be safely destroyed, or if I'll be in trouble later when tons of views like this will be created / destroyed?
Example :
var FriendListItemView = Marionette.ItemView.extend({
[...]
initialize: function(){
Marionette.ItemView.prototype.initialize.apply(this, arguments);
// get the friend and the user from global "users" collection
this.user = users.get(this.model.get('user_id'));
this.friend = users.get(this.model.get('friend_id'));
this.user.on('change:name', this.render, this);
this.friend.on('change:name', this.render, this);
},
remove: function(){
this.user.off('change:name', this.render, this);
this.friend.off('change:name', this.render, this);
this.user = null;
this.friend = null;
Marionette.ItemView.prototype.remove.apply(this, arguments);
},
});
Instead of using this.user.on('change:name', this.render, this);
use the listenTo() function.
this.listenTo(this.user, 'change:name', this.render);
Marionette will in its default destroy call the remove method from Backbone, which again will call stopListening
and clear out all event listeners registered via listenTo
. That should make your entire remove-function unnessescary. These kind of things is one of the problems that Marionette is meant to take care of for you. Setting this.user
and this.friends
to null is also unnessescary.