Backbone.js子视图未被清除

时间:2014-03-17 10:52:48

标签: javascript backbone.js backbone-views

我有以下代码

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();

我已经清楚地删除了'a'及其子视图。现在,当我新创建一个'b'OutView时,我希望在initialize console.log中打印子视图为空。但它正在打印之前的虚拟子视图。如何解决这个问题?

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

1 个答案:

答案 0 :(得分:1)

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

subviews属性的值是一个对象。对象通过引用复制,因此它将由所有DummyView实例共享。只需在initialize方法中移动instantion,为每个DummyView对象创建自己的实例:

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