Backbone.js: how to perform garbage collection on parent views, as well as child views

I applied the simple close() method to all Backbone views that have the view when it is not needed / should be reset.

 Backbone.View.prototype.close = function() { if (this.onClose) { this.onClose(); } this.remove(); this.unbind(); }; NewView = Backbone.View.extend({ el: '#List ul', initialize: function() {}, render: function() { _(this.collection.models).each(function(item) { this.renderChildren(item); }, this); }, renderChildren: function(item) { var itemView = new NewChildView({ model: item }); $(this.el).prepend(itemView.render()); }, onClose: function() { this.collection.reset(); // I want to remove the child views as well } }); NewChildView = Backbone.View.extend({ tagName: 'li', render: function() { } }); 

Now, when I delete the parent view, I also want to delete all child views. Any ideas how I can do this without getting stuck on such models ....

  _(this.collection.models).each(function(item) { item.close(); }, this); 
+7
source share
1 answer

I think that in most cases you should keep the view removal at the presentation level without affecting your models.

For example, if you delete a view with comments, perhaps another view in your application shows a selection of comments or some statistics, as well as resetting the collection will also affect these views.

Therefore, I think you should keep all this in view (including only the appropriate methods):

 NewView = Backbone.View.extend({ initialize: function() { this.childViews = []; }, renderChildren: function(item) { var itemView = new NewChildView({ model: item }); $(this.el).prepend(itemView.render()); this.childViews.push(itemView); }, onClose: function() { _(this.childViews).each(function(view) { view.close(); }); } }); 
+10
source

All Articles