SimDion
SimDion

Reputation: 1080

Marionette JS : Properly clear ItemView when listening other model events

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);
    },
});

Upvotes: 1

Views: 795

Answers (2)

Paul Falgout
Paul Falgout

Reputation: 121

just to clarify a bit further. The destroy method will also trigger events and call related methods. Additionally ItemView's initialize is a noop, so no reason to call the prototype. Most everything has before and after event hooks so you don't need to call the prototype.

var FriendListItemView = Marionette.ItemView.extend({
  [...]
  initialize: function(){
    // 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.listenTo(this.user, 'change:name' this.render);
    this.listenTo(this.friend, 'change:name' this.render);
  },
  onDestroy: function(){
    // you could do additional clean up here if you needed to
    // but you don't.  There's also an onBeforeDestroy
    // equivalent to this.on('destroy', this.doSomething);
  },
});

Upvotes: 1

ivarni
ivarni

Reputation: 17878

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.

Upvotes: 1

Related Questions