Backbone.js: Fetch a collection of models and render them Backbone.js: Fetch a collection of models and render them json json

Backbone.js: Fetch a collection of models and render them


There are 2 potential problems with your code.

  1. The event listener callback should be registered before calling the collection.fetch(). Otherwise, you might miss the first reset event as it might be triggered before the listener is registered.

  2. The reset event is not enough to ensure that the view will re-render every time the collection gets updated.

Also, note that it is a good practice to use the object.listenTo() form to bind events as it will ensure proper unregistration when the view is closed. Otherwise, you may end up with what is known as Backbone zombies. Here is a solution.

this.listenTo( this.collection, 'reset add change remove', this.render, this );this.collection.fetch({ data: { fetch:true, type:"post", page:1 } });

Note how you can register multiple events from the same object by separating them with whitespace.


change

this.collection.bind('reset', this.render, this);

to

this.collection.bind('sync', this.render, this);

The problem is you perform reset only once, in the beginning. And at that time you don't have anything to render. The next time, when you fetch your collection, reset event doesn't fire, because you fetch collection without option {reset: true}.


Change this line

this.collection.bind('reset', this.render, this);

to

this.listenTo(this.collection, 'reset', this.render);