Skip to content

Instantly share code, notes, and snippets.

@dhruvaray
Last active December 19, 2015 17:09
Show Gist options
  • Save dhruvaray/5988996 to your computer and use it in GitHub Desktop.
Save dhruvaray/5988996 to your computer and use it in GitHub Desktop.
Polymorphic associations with Backbone Associations v0.5.1+
var Models = {};
var findPolyMorphicType = Models.findPolyMorphicType = function (relation, attributes) {
var key = relation.key + '_type';
return Models[attributes[key] || this.get(key)];
};
Models.Job = Backbone.AssociatedModel.extend({
relations:[
{
type:Backbone.One,
key:'organizable',
relatedModel:findPolyMorphicType
}
]
});
Models.Comment = Backbone.AssociatedModel.extend({
relations:[
{
type:Backbone.One,
key:'commentable',
relatedModel:findPolyMorphicType
}
]
});
Models.Company = Backbone.AssociatedModel.extend({});
Models.Department = Backbone.AssociatedModel.extend({});
Models.Article = Backbone.AssociatedModel.extend({});
Models.StatusUpdate = Backbone.AssociatedModel.extend({});
var cjob = new Models.Job({organizable_type:'Company', name:"J1", organizable:{name:"Google"}});
var djob = new Models.Job({organizable_type:'Department', name:"J2", organizable:{name:"Google Reader"}});
var articleComment = new Models.Comment({
commentable_type:'Article',
name:"c1",
commentable:{body:"Wonderful post!"}
});
var statusComment = new Models.Comment({
commentable_type:'StatusUpdate',
name:"c2",
commentable:{body:"Why are you updating your status with pointless crap?"}
});
cjob.get('organizable') instanceof Models.Company === true;
djob.get('organizable') instanceof Models.Department === true;
articleComment.get('commentable') instanceof Models.Article === true;
statusComment.get('commentable') instanceof Models.StatusUpdate === true;
@dhruvaray
Copy link
Author

Thanks to @sgrif for API idea, definition and example. @monokrome for API discussions and suggestions

@dhruvaray
Copy link
Author

Available on edge version currently. Candidate for v0.5.1 release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment