Note that there are some explanatory texts on larger screens.

plurals
  1. POBackbone ListView creating zombies
    text
    copied!<p>I am trying to build a simple crud application with a view of an item and the a listView containing that item view, built from a collection. I want to have a detailView for a specific item, but when switching to this detailView, I do not know how to dispose of the listView properly. I have seen solutions for removing zombies on a single view, but not for a view composed of a collection. Is there any straight forward way to clean up a List view composed of views?</p> <pre><code>var Model = Backbone.Model.extend({ defaults : { id : '', name : '' } }); var Collection = Backbone.Collection.extend({ model : Model }) var HomeView = Backbone.View.extend({ tagName : "div", id : "home-view", initialize : function() { $("body").html(this.el); this.render(); }, render : function() { this.$el.html("&lt;h1&gt;This is the home page&lt;/h1&gt;&lt;a href='#users'&gt;Go to users&lt;/a&gt;"); } }); var UserView = Backbone.View.extend({ tagName : "li", initialize : function(e) { _.bindAll(this, "alertName"); this.render(); }, events : { "click" : "alertName" }, render : function() { this.$el.html("Hi, my name is " + this.model.get('name')); }, alertName : function() { alert(this.model.get('name')); } }); var UsersView = Backbone.View.extend({ tagName : "ul", id : "users-list", subViews : [], initialize : function(e) { $("body").html(this.el); this.collection = new Collection([{ id : '4', name : 'candy' }, { id : '2', name : 'soap' }, { id : '3', name : 'pepper' }]); console.log(this.collection) this.render(); }, render : function() { var self = this; this.collection.forEach(function(model) { var cView = new UserView({ model : model }) self.subViews.push(cView); self.$el.append(cView.el); }) this.$el.after("&lt;a href='#home'&gt;Go to home&lt;/a&gt;"); }, close : function() { while (this.subViews.length) { this.subViews.pop().remove(); } this.remove(); } }); var Router = Backbone.Router.extend({ routes : { "" : "home", "home" : "home", "users" : "users" }, initialize : function(options) { console.log('router') }, home : function(e) { console.log('home') this.loadView(new HomeView()); }, users : function(e) { console.log('users'); this.loadView(new UsersView()); }, loadView : function(view) { this.view &amp;&amp; (this.view.close ? this.view.close() : this.view.remove()); this.view = view; } }); $(document).ready(function() { var router = new Router(); Backbone.history.start({ }); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload