Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 木偶JS:在侦听其他模型事件时正确清除ItemView_Backbone.js_Marionette_Destructor_Destroy - Fatal编程技术网

Backbone.js 木偶JS:在侦听其他模型事件时正确清除ItemView

Backbone.js 木偶JS:在侦听其他模型事件时正确清除ItemView,backbone.js,marionette,destructor,destroy,Backbone.js,Marionette,Destructor,Destroy,当项目视图正在侦听其模型(this.model)以外的模型时,我是否只需要在删除功能中关闭侦听器?并将其引用设置为null?我想知道项目视图是否会被安全地销毁,或者当大量这样的视图被创建/销毁时,我是否会遇到麻烦 例如: var FriendListItemView = Marionette.ItemView.extend({ [...] initialize: function(){ Marionette.ItemView.prototype.initializ

项目视图正在侦听其模型(this.model)以外的模型时,我是否只需要在删除功能中关闭侦听器?并将其引用设置为null?我想知道项目视图是否会被安全地销毁,或者当大量这样的视图被创建/销毁时,我是否会遇到麻烦

例如:

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

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

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

木偶网将在其默认情况下从主干网调用该方法,该方法将再次调用
停止侦听
,并清除通过
侦听器注册的所有事件侦听器
。这将使您的整个删除功能变得不那么可怕。这类事情是木偶要为你解决的问题之一。将
this.user
this.friends
设置为null也没有必要。

只是为了进一步澄清一下。destroy方法还将触发事件并调用相关方法。此外,ItemView的initialize是一个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);
  },
});

这正是我想要的。很好,完整和清晰的答案,谢谢伊瓦尼!如果您不手动调用this.model.destroy(),则可以通过我自己的测试使用木偶浏览器;在onDestroy()中,模型永远不会被破坏。@Groviel我很想看到这种行为的演示,因为我刚刚链接到明确调用这些方法的源代码。这可能是旧版本吗?