Backbone.js - fetch method does not fire reset event

chr1s picture chr1s · Apr 11, 2013 · Viewed 9.1k times · Source

I'm beginning with Backbone.js and trying to build my first sample app - shopping list.

My problem is when I fetch collection of items, reset event isn't probably fired, so my render method isn't called.

Model:

Item = Backbone.Model.extend({
  urlRoot : '/api/items',
  defaults : {
    id : null,
    title : null,
    quantity : 0,
    quantityType : null,
    enabled : true
  }
});

Collection:

ShoppingList = Backbone.Collection.extend({
  model : Item,
  url : '/api/items'
});

List view:

ShoppingListView = Backbone.View.extend({

el : jQuery('#shopping-list'),

initialize : function () {
    this.listenTo(this.model, 'reset', this.render);
},

render : function (event) {
    // console.log('THIS IS NEVER EXECUTED');
    var self = this;
    _.each(this.model.models, function (item) {
        var itemView = new ShoppingListItemView({
            model : item
        });
        jQuery(self.el).append(itemView.render().el);
    });
    return this;
}

});

List item view:

ShoppingListItemView = Backbone.View.extend({

tagName : 'li',

template : _.template(jQuery('#shopping-list-item').html()), // set template for item

render : function (event) {
    jQuery(this.el).html(this.template(this.model.toJSON()));
    return this;
}

});

Router:

var AppRouter = Backbone.Router.extend({

routes : {
    '' : 'show'
},

show : function () {
    this.shoppingList = new ShoppingList();
    this.shoppingListView = new ShoppingListView({
        model : this.shoppingList
    });
    this.shoppingList.fetch(); // fetch collection from server
}

});

Application start:

var app = new AppRouter();
Backbone.history.start();

After page load, collection of items is correctly fetched from server but render method of ShoppingListView is never called. What I am doing wrong?

Answer

Eric Hu picture Eric Hu · Apr 11, 2013

Here's your problem:

" When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}" Backbone Docs

So, you want to fire the fetch with the reset option:

this.shoppingList.fetch({reset:true}); // fetch collection from server

As an aside, you can define a collection attribute on a view:

this.shoppingList = new ShoppingList();
  this.shoppingListView = new ShoppingListView({
     collection : this.shoppingList  // instead of model: this.shoppingList
  });