Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does collection.fetch({add:true}) work?

I added a model to my collection and did model.save The data gets saved on the server.

After this I call collection.fetch({add:true}). Ideally only one model should be returned from server ie the newly added one but I'm seeing the entire collection being propagated back in chrome developers tool.

I'm confused. how does this actually work ?

like image 961
Abhishek Avatar asked Apr 11 '13 07:04

Abhishek


1 Answers

As an add-on to Cyril N.'s answer (which describes essentially the default behavior, and should be enough I guess), I'd like to explain more thoroughly the role of the 3 flags:

  • add: whether or not Backbone should create and add to the collection the models which don't exist yet (ie, whose id are not in the collection)
  • remove: whether or not Backbone should remove from the collection the models which were not brought back from the server (ie, whose id were not is the brought back data)
  • merge: whether or not Backbone should update the models which are not in the first two categories (already in the collection, and brought back from the server)

However, I like to expand a bit further about the general behavior of the method (it uses the Collection#set method as a callback, so it's more the Collection#set's behavior). Backbone prepares the models, which means it creates fake, volatile models at the beginning of the method (they're only volatile if they're not added). This can lead to unexpected behaviors: because it creates models, the initialize method of those are executed.

Also, as a side-note, since Backbone 1.0, the Collection#reset flag was introduced if you want to reset your collection when fetching (therefore it uses this method as a callback). Before that, it was the default behavior of the Collection#fetch method.

Well, with both answers you should have every info you need I guess.

like image 165
Loamhoof Avatar answered Oct 08 '22 14:10

Loamhoof