Skip to content

Instantly share code, notes, and snippets.

@boronine
Created September 25, 2012 22:06
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 boronine/3784763 to your computer and use it in GitHub Desktop.
Save boronine/3784763 to your computer and use it in GitHub Desktop.
Backbone collection live filtering (untested)
Backbone.Collection.prototype.liveFilter = function(attributes) {
// Make a clone of the collection instantiated with all the filtered items
var _org = this;
var _new = new this.constructor(this.where(attributes));
// What happens when you add to the original collection?
_org.on('add', function(model) {
// Unless one of the attributes doesn't match
for (key in attributes) {
if (model.get(key) !== attributes[key]) return;
}
// Add the model to our new collection
_new.add(model);
});
_org.on('remove', function(model) {
for (key in attributes) {
if (model.get(key) !== attributes[key]) return;
}
_new.remove(model);
});
_new.on('add', function(model) {
for (key in attributes) {
if (model.get(key) !== attributes[key]) return;
}
_org.add(model);
});
_new.on('remove', function(model) {
for (key in attributes) {
if (model.get(key) !== attributes[key]) return;
}
_org.remove(model);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment