Skip to content

Instantly share code, notes, and snippets.

@stephenaument
Last active August 29, 2015 13:57
Show Gist options
  • Save stephenaument/9541718 to your computer and use it in GitHub Desktop.
Save stephenaument/9541718 to your computer and use it in GitHub Desktop.
Backbone Collection Testing Gotcha
/* Excerpt starting at line 785 */
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, length = this.models.length; i < length; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
/* Except starting at line 718 */
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
models[i] = existing;
If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true}, in which case their attributes will be merged into the corresponding models, firing any appropriate "change" events.
providerArray = (new WellMatch.Models.Provider(display_name: 'a') for [1..18])
providers = new WellMatch.Collections.Providers(providerArray)
Providers {fullParams: function, length: 1, models: Array[1], _byId: Object, _events: Object…}
provider = new WellMatch.Models.Provider({display_name: 'a'})
providerArray = (provider for [1..18])
providers = new WellMatch.Collections.Providers(providerArray)
Providers {fullParams: function, length: 1, models: Array[18], _byId: Object, _events: Object…}
provider = new WellMatch.Models.Provider({display_name: 'a'})
providers = new WellMatch.Collections.Providers()
providers.models = providerArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment