Question

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/

Was it helpful?

Solution

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 = {};
  }, 
  ...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top