Backbone.js - the extraction method does not fire a reset event

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(); // fetch collection from server } }); 

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?

+6
source share
2 answers

Here is your problem:

"When model data is returned from the server, it uses set (sensibly) to combine the extracted models if you fail {reset: true}" Trunk documents

So, you want to start the selection using the reset option:

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

Aside, you can define the collection attribute in the view :

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

Are you using Backbone 1.0? If not, ignore this, otherwise you may find what the dock says about Collection # fetch , interesting.

To quote the change log:

"Renamed collection" update "to set parallelism to the same model.set () and contrast with reset. Now this is the default update mechanism after extraction. If you want to continue using" reset ", pass {reset: true}"

So, you do not reset here, but update , so the reset event does not fire.

+1
source

All Articles