简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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