Skip to content

Instantly share code, notes, and snippets.

@dhruvaray
Created October 18, 2013 09:44
Show Gist options
  • Save dhruvaray/7039163 to your computer and use it in GitHub Desktop.
Save dhruvaray/7039163 to your computer and use it in GitHub Desktop.
Use Polymorphic models in 1:M relations
var Club = Backbone.AssociatedModel.extend({
relations:[{
type:Backbone.Many,
key:'members',
relatedModel:function (relation, attributes) {
return function (attrs, options) {
if (_.isArray(attrs.dependents)) {
return new Employee(attrs);
}
return new Dependent(attrs);
}
}
}],
defaults:{
name:"",
members:[]
},
urlRoot:'/club'
});
var club = new Club({
name:"Club X"
});
club.set({
members: [{
fname: "John",
lname: "Smith",
age: 21,
sex: "M",
dependents: [child1, child2]
}, {
fname: "Edgar",
lname: "Smith",
sex: "M",
relationship: "P"
}]
});
console.log(club.get('members[0]') instanceof Employee); //true
console.log(club.get('members[1]') instanceof Dependent)//true;
@dhruvaray
Copy link
Author

Contributed by @dak

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