I start with Backbone.js and try to create my first example application - a shopping list.
My problem is that when I get a collection of elements, the reset event does not fire, so my render method is not 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' });
View List:
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; } });
View a list of items:
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();
Application start:
var app = new AppRouter(); Backbone.history.start();
After loading the page, the collection of elements is correctly selected from the server, but the renderListView method is never called. What am I doing wrong?