Created
April 4, 2013 05:59
-
-
Save RabidFire/5308182 to your computer and use it in GitHub Desktop.
Backbone Subset
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
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