Created
September 25, 2012 22:06
-
-
Save boronine/3784763 to your computer and use it in GitHub Desktop.
Backbone collection live filtering (untested)
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.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