简体   繁体   English

Backbone.js子视图未清除

[英]Backbone.js subviews not getting cleared

I have the following code 我有以下代码

var DummyView = Backbone.View.extend({
  subviews: {}, 
  remove: function() {
    console.log('dummy remove');
    _.invoke(this.subviews, 'remove');
    this.subviews = {}; 

    Backbone.View.prototype.remove.apply(this, arguments);
  }
});

var StartView = Backbone.View.extend({
  subviews: {}, 

  initialize: function() {
    console.log('Start initialize');
    seen = []; 
    console.log(JSON.stringify(this.subviews,  function(key, val) {
        if (typeof val == "object") {
            if (seen.indexOf(val) >= 0) {
                return;
            }   
            seen.push(val);
        }   
        return val;
    }));
    this.subviews['dummy'] = new DummyView();
  },

  remove: function() {
    console.log('start remove');
    _.invoke(this.subviews, 'remove');
    this.subviews = {};
    Backbone.View.prototype.remove.apply(this, arguments);
  }
});

var a = new StartView();
a.remove();
delete a;
console.log('creating b and expecting b subviews to be empty');
var b = new StartView();

I've clearly removed 'a' and its subviews. 我清楚地删除了“ a”及其子视图。 Now when I newly create a 'b' StartView, I expected the subviews to be empty printed in the initialize console.log. 现在,当我新创建一个'b'StartView时,我希望子视图在初始化console.log中打印为空。 But it is printing the previous dummy subview. 但是它正在打印以前的虚拟子视图。 How to solve this issue? 如何解决这个问题?

Find JSFiddle here - http://jsfiddle.net/ZWM89/3/ 在这里找到JSFiddle- http://jsfiddle.net/ZWM89/3/

var DummyView = Backbone.View.extend({
  subviews: {}, 
  ...
});

The value of the subviews property is an object. subviews属性的值是一个对象。 Objects are copied by reference, therefore it instance will be shared by all DummyView instances. 对象是通过引用复制的,因此该实例将被所有DummyView实例共享。 Just move instantion in the initialize method to create own instance for each DummyView object: 只需在initialize方法中移动实例,即可为每个DummyView对象创建自己的实例:

var DummyView = Backbone.View.extend({
  initialize: function() { 
      this.subviews = {};
  }, 
  ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM