Marionette JS:在收听其他模型事件时正确清除ItemView

时间:2015-09-02 16:40:14

标签: backbone.js marionette destructor destroy

ItemView 正在侦听模型(this.model)以外的模型时,我是否只需要在删除函数中关闭侦听器?并将其引用设置为null?我想知道 ItemView 是否会被安全销毁,或者如果我以后会遇到很多类似的视图会被创建/销毁?

示例:

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

2 个答案:

答案 0 :(得分:1)

而不是使用this.user.on('change:name', this.render, this);使用listenTo()函数。

this.listenTo(this.user, 'change:name', this.render);

Marionette将默认destroy调用Backbone中的remove方法,该方法将再次调用stopListening并清除通过listenTo注册的所有事件侦听器。这应该使你的整个删除功能unnessescary。这些事情是Marionette为您照顾的问题之一。将this.userthis.friends设置为null也是不合格的。

答案 1 :(得分:1)

只是为了进一步澄清。 destroy方法还将触发事件并调用相关方法。另外,ItemView的初始化是一个noop,因此没有理由调用原型。大多数事情都有事件挂钩之前和之后所以你不需要调用原型。

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);
  },
});
相关问题