Skip to content

Instantly share code, notes, and snippets.

@thegrubbsian
Created March 18, 2012 19:09
Show Gist options
  • Save thegrubbsian/2079927 to your computer and use it in GitHub Desktop.
Save thegrubbsian/2079927 to your computer and use it in GitHub Desktop.
Nested/Bound Collections in Backbone
// Trigger a modelChanged event on a model's collection if it has one
Backbone.Model.prototype.change = (function(original) {
return function(options) {
if (this.collection) {
this.collection.trigger("modelChange", this, options);
}
original.call(this, options);
};
})(Backbone.Model.prototype.change);
// Create's child collections that are 'bound' to their parent
Backbone.Collection.prototype.createChild = function(name, filterFunc, options) {
var self = this;
if (!options) { options = {}; }
if (!this.children) { this.children = {}; }
var collection = new Backbone.Collection(this.filter(filterFunc), options);
_.each(collection.models, function(m) { m.collection = collection; });
collection.filterFunction = filterFunc;
collection.parent = this;
this.children[name] = collection;
this.bind("add", reassignModel);
this.bind("remove", reassignModel);
this.bind("modelChange", reassignModel);
collection.bind("add", reassignModel);
collection.bind("remove", reassignModel);
collection.bind("modelChange", reassignModel);
function reassignModel(model) {
_.each(self.children, function(col) {
if (!col.filterFunction(model) && col.get(model.id)) {
col.remove(model);
}
});
_.each(self.children, function(col) {
if (col.filterFunction(model) && !col.get(model.id)) {
col.add(model);
model.collection = col;
}
});
}
return collection;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment