Created
August 7, 2012 20:55
-
-
Save jjulian/3289267 to your computer and use it in GitHub Desktop.
Backbone.js collection upsert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); }); | |
}, | |
} |
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
An optimization to removing unwanted models from a collection. See the "generic method" answer at http://stackoverflow.com/questions/9640095/backbone-js-collection-upsert