PaulUithol/Backbone-relational — pull request #111 by DouweM (2012-04-19 21:27:24+00:00)
Title: Replaces #87: Add support for submodels.

Replaces #87, and based on comments over there.

**Quick overview of new `Backbone.RelationalModel.extend` options**

> `partOfSupermodel`: `true` if this model should use the same model collection and relations as its superclass.
>
> `submodelTypeAttribute`: attribute that should be checked to determine the type of object to build when attributes are passed in. Default: `type`
>
> `submodelType`: value of attribute defined using `submodelTypeAttribute` that will cause this type of object to be built.

I'll add some proper documentation to the README tomorrow, but if you'd like you can read through the diff already.

**Example**

```javascript
var PetAnimal = Backbone.RelationalModel.extend({
});
var Dog = PetAnimal.extend({
partOfSupermodel: true,
submodelType: 'dog'
});
var Cat = PetAnimal.extend({
partOfSupermodel: true,
submodelType: 'cat'
});

var PetPerson = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'pets',
relatedModel: PetAnimal,
reverseRelation: {
key: 'owner'
}
}]
});

var person = new PetPerson({
pets: [{
type: 'dog',
name: 'Spot'
},
{
type: 'cat',
name: 'Whiskers'
}]
});

ok( person.get('pets').at(0) instanceof Dog );
ok( person.get('pets').at(1) instanceof Cat );

person.get('pets').add({
type: 'dog',
name: 'Spot II'
});

ok( person.get('pets').at(2) instanceof Dog );
```