I'm building an app with Backbone.js. Some of my server-side APIs will return me all the new or changed models since a particular time. Some of those objects may be new to my collection so I can just add them. Others may already exist, in which case I'd like to update the existing model. So basically I'm looking for upsert (update-or-insert) functionality.
This is similar to the {add:true} option that was added in 0.9.0, except that I also want updating.
Is there an easy/known way to do this? It doesn't seem hard to update the code, but I don't want to reinvent a wheel.
I have solved this situation in a generic method:
Params
collection
: is a Backbone.CollectioncollectionJSON
: is an Array with the models data in Hash style.. typical JSON response.I'm sure it can be optimized, especially the remove part. But I keep it like this for readability due I'm still making tests.
Example of use
NOTE: This answer was written for Backbone v0.9. Since then Backbone v1.0 has released, which contains the
collection.set()
method described here. That will likely be a better solution.I threw together my own version of this over the weekend. I'll put it up here in case anybody else finds this thread, but I'd still be happy to see any other solutions that might be out there.
I did this by modifying the Backbone.js source, which is not necessarily a great idea, but it was easy. There were two changes, first add this function to the Backbone.Collection prototype:
Then modify one line in the Backbone.Collection.fetch() function to read:
This allows you to call
fetch({upsert:true})
to get the behavior I was looking for.