Skip to content

Instantly share code, notes, and snippets.

@RabidFire
Created April 4, 2013 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RabidFire/5308182 to your computer and use it in GitHub Desktop.
Save RabidFire/5308182 to your computer and use it in GitHub Desktop.
Backbone Subset
Backbone.Subset = Backbone.Collection.extend({
superset: null,
initialize: function(models, options){
this.superset = options.superset || this.superset;
this.sieve = options.sieve || this.sieve;
if (!this.superset) throw new Error('Missing superset for Backbone.Subset');
_.each(['add', 'remove', 'reset', 'change'], function(evt){
this.superset.on(evt, this.setModels, this);
}, this);
this.setModels();
},
setModels: function(){
this.set(this.superset.filter(this.sieve));
},
sieve: function(model){
return true;
}
});
// Usage
var completedModels = new Backbone.Subset(null, {
superset: App.models,
sieve: function(model){
return model.get('isCompleted');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment