Updating a collection using fetch with a framework

Based on the official documentation, when I do something like this:

collection.fetch({update: true, remove: false}) 

I get an โ€œaddโ€ event for each new model and a โ€œchangeโ€ event for every modified existing model without deleting anything.

Why, if I call a static data source (the collection URL always returns the same json), the add event is fired for each item received?

Here is the code (I am not doing anything, I am just debugging):

 <!doctype html> <html> <head> <title>Example</title> </head> <body> <a href="#refresh">Refresh</a> <script src="js/jquery-1.8.3.min.js"></script> <script src="js/underscore-min.js"></script> <script src="js/backbone-min.js"></script> <script src="js/main.js"></script> </body> </html> 

Heres the JS

 (function($){ //Twitter Model ModelsTwitt = Backbone.Model.extend({}); //Twitter Collection CollectionsTwitts = Backbone.Collection.extend({ model:ModelsTwitt, initialize:function(){ console.log('Twitter App Started'); }, url:'data/195.json' }); //Twitts View ViewsTwitts = Backbone.View.extend({ el:$('#twitter-list'), initialize:function(){ _.bindAll(this, 'render'); this.collection.bind('reset',this.render); this.collection.bind('add',this.add); }, render:function(){ console.log("This is the collection",this.collection); }, add:function(model){ console.log("add event called",model); } }); //Twitter Router Router = Backbone.Router.extend({ routes:{ '':'defaultRoute',//Default list twitts route 'refresh':'refreshView' }, defaultRoute:function(){ this.twitts = new CollectionsTwitts(); new ViewsTwitts({collection:this.twitts}); this.twitts.fetch(); }, refreshView:function(){ this.twitts.fetch({update:true,remove:false}); } }); var appRouter = new Router(); Backbone.history.start(); })(jQuery); 

Basically, I select a collection using the default function, it is correctly selected with all models and attributes.

And when I click the refresh link, I call refreshView, which basically tries to update the collection with new models. I donโ€™t understand why, if the answer is the same, all the collection models appear as new, causing an addition?

It has a functional link: open the console and you will see how add events are raised when the update is clicked, even when the collection is the same.

Thank you for your help.

+7
source share
1 answer

I assume your models do not have idAttribute (doc) . The main Backbone key for searching is id , and your JSON entries do not have one, so it cannot determine which models already exist.

Try changing the model to this (or another key, if it is not unique):

 ModelsTwitt = Backbone.Model.extend({ idAttribute: 'id_event' }); 
+12
source

All Articles