I’m trying to do basic render() after fetch() on collection (Backbone 0.9.2):
var ProjectListView = Backbone.View.extend({
el: $('#container'),
initialize: function () {
this.collection = new ProjectsCollection();
this.collection.bind("change", _.bind(this.render, this));
this.collection.fetch({ success: function () { console.log("collection fetched"); } });
...
},
render: function () {
console.log("rendered");
...
Creating new View instance prints out:
collection fetched
So the render() never gets called after fetch(). What am I doing wrong here? There are no exceptions present.
Any tips how to debug these sort of things in backbone?
Ps.
It seems that this feature is poorly documented given the number of questions on SO.
From the fine manual:
And what does
resetdo?resetdoes this:So
fetchcallsresetto update the collection’s models andresettriggers a"reset"event, not a"change"event. None of the models have changed and a collection’s"change"events come from its models.You should have
renderbound to"reset":If you want to listen for
"change"events on the contained models then you can bind a"change"handler to the collection since:The collection will also generate
"add"and"remove"events as the collection itself changes.Newer versions of Backbone no longer reset collections during
fetch:And
set:So with newer versions of Backbone you’ll want to list for the
"add","remove", and"change"events (which a collection based view should be listening for anyway); you could also use{reset: true}on the initialfetchand listen to"reset"as well. I’d recommend the following approach for collection based views:"add"and handle that event with a callback that simply adds one item to the view, don’t throw everything away and re-render."remvoe"and handle that event with a callback that only removes the newly removed model."change"and handle that with a callback that replaces (or updates) the appropriate item."reset"and bind that torender. Then pass{reset: true}to the collection’s initialfetchcall.That will trap the important events and the collection-view will do the minimal amount of work to handle each one. Of course, this strategy isn’t applicable to all situations but I think it is a good starting point.