문제

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. Now when I newly create a 'b' StartView, I expected the subviews to be empty printed in the initialize console.log. But it is printing the previous dummy subview. How to solve this issue?

Find JSFiddle here - http://jsfiddle.net/ZWM89/3/

도움이 되었습니까?

해결책

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

The value of the subviews property is an object. Objects are copied by reference, therefore it instance will be shared by all DummyView instances. Just move instantion in the initialize method to create own instance for each DummyView object:

var DummyView = Backbone.View.extend({
  initialize: function() { 
      this.subviews = {};
  }, 
  ...
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top