Skip to content

Instantly share code, notes, and snippets.

@scottharvey
Created April 18, 2011 05:20
Show Gist options
  • Save scottharvey/924852 to your computer and use it in GitHub Desktop.
Save scottharvey/924852 to your computer and use it in GitHub Desktop.
This snippet allows you to define relationships between you backbone models
$.extend(Backbone.Model.prototype, {
hasMany: function(collectionName, associationColumn, opts) {
var parent = this,
associationName = (collectionName.substr(0, 1).toLowerCase() + collectionName.substr(1)),
options = $.extend({ parentId: 'id' }, opts),
collection;
this[associationName] = function() {
collection = window[collectionName].select(function(child) {
return child.get(associationColumn) == parent.get(options['parentId']);
});
return new pimms.model[collectionName](collection);
};
},
belongsTo: function(collectionName, associationColumn) {
var child = this,
associationName = (collectionName.substr(0, 1).toLowerCase() + collectionName.substr(1)).replace(/s$/, '');
this[associationName] = function() {
return window[collectionName].detect(function(parent) {
return child.get(associationColumn) == parent.get('id');
});
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment