Skip to content

Instantly share code, notes, and snippets.

@jjulian
Created August 7, 2012 20:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjulian/3289267 to your computer and use it in GitHub Desktop.
Save jjulian/3289267 to your computer and use it in GitHub Desktop.
Backbone.js collection upsert
App.Utils = {
refreshCollection: function( collection, collectionJSON ){
// update/add
_( collectionJSON ).each( function( modelJSON ) {
modelJSON._touched = true; // MARK THE ONES TO KEEP
var model = collection.get( modelJSON.id );
if( model ) {
model.set( modelJSON );
} else {
collection.add( modelJSON );
}
});
// REMOVE THE UNMARKED
collection.remove(collection.filter(function(m) { return !m.get('_touched'); }));
// CLEAN UP
collection.each(function(m) { m.unset('_touched', {silent: true}); });
},
}
@jjulian
Copy link
Author

jjulian commented Aug 7, 2012

An optimization to removing unwanted models from a collection. See the "generic method" answer at http://stackoverflow.com/questions/9640095/backbone-js-collection-upsert

@kpwebb
Copy link

kpwebb commented Feb 1, 2013

This doesn't quite work -- the _touched flag seems to trigger a change event that causes the model to re-render even though no change has occurred. The approach suggested in the original post is better in this sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment