Backbone-relational.js

When developing any medium to large-scale web application, you often get to the point where an action by a user can cause a number of different models to change on the client and the server.

You can try to keep updating both sides of a relation manually for every action, and individually call save or fetch on each of the changed models to sync with the server, but that quickly turns into a tedious process and results in multiple requests.

Using Backbone-relational, we can configure relationships between our models, and sync the model and all of its related models with a single call to save, getAsync or fetch() after setting up a model's relations.

Backbone-relational is hosted on GitHub, and is available under the MIT license.

Thanks to Progressive Planning for allowing me the time to work on Backbone-relational!

Downloads & Dependencies (Right-click, and use "Save As")

Latest Release (0.10.0) ~70kb. Full source, uncompressed, lots of comments.
Edge Version

Backbone-relational depends on Backbone.js (>= 1.2.1), which itself requires Underscore.js (> 1.7.0) and jQuery (> 1.7.0) or Zepto.

Introduction

Backbone-relational.js provides one-to-one, one-to-many and many-to-one relations between models for Backbone. To use relations, extend Backbone.RelationalModel (instead of a regular Backbone.Model) and define a relations property, containing an array of option objects. Each relation must define (at least) the type, key, and relatedModel. Available relation types are Backbone.HasOne and Backbone.HasMany.

Backbone-relational's main features include:

You can also bind new events to a Backbone.RelationalModel for an:

Installation

Backbone-relational depends on Backbone.js (and thus on Underscore.js). Include Backbone-relational right after Backbone and Underscore:

<script type="text/javascript" src="./js/underscore.js"></script>
<script type="text/javascript" src="./js/backbone.js"></script>
<script type="text/javascript" src="./js/backbone-relational.js"></script>

Note for CoffeeScript users: due to the way the extends keyword is implemented in CoffeeScript, you may have to make an extra call to setup for your models. See the setup documentation for details.

Backbone.RelationalModel

When using Backbone-relational, each model defining (or receiving) relations must extend Backbone.RelationalModel in order to function. Backbone.RelationalModel introduces a couple of new methods, events and properties. It's important to know which are properties, which are methods of an instance, and which operate on the type itself. These three categories are detailed below.

Properties can be defined when extending Backbone.RelationalModel, or a subclass thereof.

Instance methods operate on an instance of a type.

Static methods operate on the type itself, as opposed to operating on model instances.

Properties

relationsrelation[]

A Backbone.RelationalModel may contain an array of relation definitions. Each relation supports a number of options, of which key and type are mandatory. You'll also need to specifiy relatedModel if you want to reference another model. A relation could look like the following:

Zoo = Backbone.RelationalModel.extend({
	relations: [{
		type: Backbone.HasMany,
		key: 'animals',
		relatedModel: 'Animal',
		collectionType: 'AnimalCollection',
		reverseRelation: {
			key: 'livesIn',
			includeInJSON: 'id'
			// 'relatedModel' is automatically set to 'Zoo'; the 'relationType' to 'HasOne'.
		}
	}]
});

Animal = Backbone.RelationalModel.extend({
	urlRoot: '/animal/'
});

AnimalCollection = Backbone.Collection.extend({
	model: Animal
});

// We've now created a fully managed relation. When you add or remove model from `zoo.animals`,
// or update `animal.livesIn`, the other side of the relation will automatically be updated.
var artis = new Zoo( { name: 'Artis' } );
var lion = new Animal( { species: 'Lion', livesIn: artis } );

// `animals` in `artis` now contains `lion`
alert( artis.get( 'animals' ).pluck( 'species' ) );
var amersfoort = new Zoo( { name: 'Dierenpark Amersfoort', animals: [ lion ] } );

// `lion` now livesIn `amersfoort`, and `animals` in `artis` no longer contains `lion`
alert( lion.get( 'livesIn' ).get( 'name' ) + ', ' + artis.get( 'animals' ).length );

keyrelation.key

Required. A string that references an attribute name on relatedModel.

relatedModelrelation.relatedModel

A string that can be resolved to an object on the global scope, or a reference to a Backbone.RelationalModel. Also see addModelScope.

If omitted, the relation will be self-referential.

typerelation.type

Required. A string that references a Backbone.Relation type by name ("HasOne" or "HasMany"), or a direct reference to a relation type.

You can model a one-to-one or a many-to-one relationship by declaring type as the string "HasOne", or by directly referencing Backbone.HasOne. A HasOne relation contains a single Backbone.RelationalModel. The default reverseRelation.type for a "HasOne" relation is "HasMany". This can be set to "HasOne" instead, to create a one-to-one relation.

You can model a one-to-many relationship by declaring type as the string "HasMany", or by directly referencing Backbone.HasMany. A HasMany relation contains a Backbone.Collection, containing zero or more Backbone.RelationalModels. The default reverseRelation.type for a HasMany relation is HasOne; this is the only option here, since many-to-many is not supported directly.

It is possible to model a many-to-many relationship using two Backbone.HasMany relations, with a link model in between:

Person = Backbone.RelationalModel.extend({
	relations: [{
		type: 'HasMany',
		key: 'jobs',
		relatedModel: 'Job',
		reverseRelation: {
			key: 'person'
		}
	}]
});

// A link object between 'Person' and 'Company'
Job = Backbone.RelationalModel.extend({
	defaults: {
		'startDate': null,
		'endDate': null
	}
});

Company = Backbone.RelationalModel.extend({
	relations: [{
		type: 'HasMany',
		key: 'employees',
		relatedModel: 'Job',
		reverseRelation: {
			key: 'company'
		}
	}]
});

includeInJSONrelation.includeInJSON

A boolean, a string referencing one of the model's attributes, or an array of strings referencing model attributes. Default: true.

Determines how the contents of a relation will be serialized following a call to the toJSON method. If you specify a:

  • Boolean: a value of true serializes the full set of attributes on the related model(s). Set to false to exclude the relation completely.
  • String: include a single attribute from the related model(s). For example, 'name', or Backbone.Model.prototype.idAttribute to include ids.
  • String[]: includes the specified attributes from the related model(s).

Specifying true will cascade, meaning the relations of nested model will get serialized as well, until either a different value is found for includeInJSON or we encounter a model that has already been serialized.

autoFetchrelation.autoFetch

A boolean or an object. Default: false.

If this property is set to true, when a model is instantiated the related model is automatically fetched using getAsync. The value of the property can also be an object. In that case the object is passed to getAsync as the options parameter.

Note that autoFetch operates independently from other `fetch` operations, including those that may have fetched the current model.

var Shop = Backbone.RelationalModel.extend({
	relations: [
		{
			type: Backbone.HasMany,
			key: 'customers',
			relatedModel: 'Customer',
			autoFetch: true
		},
		{
			type: Backbone.HasOne,
			key: 'address',
			relatedModel: 'Address',
			autoFetch: {
				success: function( model, response ) {
					//...
				},
				error: function( model, response ) {
					//...
				}
			}
		}
	]
});

collectionTyperelation.collectionType

A string that can be resolved to an object type on the global scope, or a reference to a Backbone.Collection type.

Determine the type of collections used for a HasMany relation. If you define a url(models<Backbone.Model[]>) function on the specified collection, this enables getAsync to fetch all missing models in one request, instead of firing a separate request for each.

collectionKeyrelation.collectionKey

A string or a boolean. Default: true.

Used to create a back reference from the Backbone.Collection used for a HasMany relation to the model on the other side of this relation. By default, the relation's key attribute will be used to create a reference to the RelationalModel instance from the generated collection. If you set collectionKey to a string, it will use that string as the reference to the RelationalModel, rather than the relation's key attribute. If you don't want this behavior at all, set collectionKey to false (or any falsy value) and this reference will not be created.

collectionOptionsrelation.collectionOptions

An options hash, or a function that accepts an instance of a Backbone.RelationalModel and returns an options hash.

Used to provide options for the initialization of the collection in the 'Many'-end of a HasMany relation. Can be an options hash or a function that should take the instance in the 'One'-end of the 'HasMany' relation and return an options hash.

createModelsrelation.createModels

A boolean. Default: true.

Specifies whether models will be created from nested objects or not.

keySourcerelation.keySource

A string that references an attribute to deserialize data for relatedModel from.

Used to override key when determining what data to use when (de)serializing a relation, since the data backing your relations may use different naming conventions. For example, a Rails backend may provide the keys suffixed with _id or _ids. The behavior for keySource corresponds to the following rules:

When a relation is instantiated, the contents of the keySource are used as its initial data. The application uses the regular key attribute to interface with the relation and the models in it; the keySource is not available as an attribute for the model. So you may be provided with data containing animal_ids, while you want to access this relation as zoo.get('animals').

Note that setting keySource will set keyDestination to the same value, if it isn't specified itself. This means that when saving zoo, the animals attribute will be serialized back into the animal_ids key.

WARNING: when using a keySource, you should not use that attribute name for other purposes.

keyDestinationrelation.keyDestination

A string that references an attribute to serialize relatedModel into.

Used to override key (and keySource) when determining what attribute to be written into when serializing a relation, since the server backing your relations may use different naming conventions. For example, a Rails backend may expect the keys to be suffixed with _attributes for nested attributes.

When calling toJSON on a model (either via Backbone.Sync, or directly), the data in the key attribute is transformed and assigned to the keyDestination.

So you may want a relation to be serialized into the animals_attributes key, while you want to access this relation as zoo.get( 'animals' );.

WARNING: when using a keyDestination, you should not use that attribute name for other purposes.

var FarmAnimal = Animal.extend();

// This `Farm` is confused, like legacy stuff can be. It wants its data back on a completely
// different key than it supplies it on. We want to use a different one in our app as well.
var Farm = Backbone.RelationalModel.extend({
	relations: [{
		type: Backbone.HasMany,
		key: 'animals',
		keySource: 'livestock',
		keyDestination: 'pets',
		relatedModel: FarmAnimal,
		reverseRelation: {
			key: 'farm',
			includeInJSON: 'name'
		}
	}]
});

// Create a `Farm`; parse `species`, add to `animals`, output goes to `pets`.
var farm = new Farm( { name: 'Old MacDonald', livestock: [ { species: 'Sheep' } ] } );
farm.get( 'animals' ).add( { species: 'Cow' } );
alert( JSON.stringify( farm.toJSON(), null, 4 ) );

parserelation.parse

A boolean. Default: false.

If you have a relation where the models should be parsed when data is being set, specify `parse: true`.

reverseRelationrelation.reverseRelation

An object specifying the relation pointing back to this model from relatedModel.

If the relation should be bidirectional, specify the details for the reverse relation here. It's only mandatory to supply a key; relatedModel is automatically set. The default type for a reverseRelation is HasMany for a HasOne relation (which can be overridden to HasOne in order to create a one-to-one relation), and HasOne for a HasMany relation. In this case, you cannot create a reverseRelation with type HasMany as well; please see Many-to-many relations on how to model these type of relations.

Note that if you define a relation (plus a reverseRelation) on a model, but don't actually create an instance of that model, it is possible initializeRelations will never get called, and the reverseRelation will not be initialized. This can happen when extend has been overridden, or redefined as in CoffeeScript. See setup.

subModelTypesrelationalModel.subModelTypes(attributes<object>, [options<object>])

An object. Default: {}.

A mapping that defines what submodels exist for the model (the superModel) on which subModelTypes is defined. The keys are used to match the subModelTypeAttribute when deserializing, and the values determine what type of submodel should be created for a key. When building model instances from data, we need to determine what kind of object we're dealing with in order to create instances of the right subModel type. This is done by finding the model for which the key is equal to the value of the subModelTypeAttribute attribute on the passed in data.

Each subModel is considered to be a proper submodel of its superclass (the model type you're extending), with a shared id pool. This means that when looking for an object of the supermodel's type, objects of a submodel's type can be returned as well, as long as the id matches. In effect, any relations pointing to the supermodel will look for instances of its submodels as well.

Mammal = Animal.extend({
	subModelTypes: {
		'primate': 'Primate',
		'carnivore': 'Carnivore'
	}
});

Primate = Mammal.extend();
Carnivore = Mammal.extend();

MammalCollection = AnimalCollection.extend({
	model: Mammal
});

// Create a collection that contains a 'Primate' and a 'Carnivore'.
var mammals = new MammalCollection([
	{ id: 3, species: 'chimp', type: 'primate' },
	{ id: 5, species: 'panther', type: 'carnivore' }
]);

var chimp = mammals.get( 3 );

alert( 'chimp is an animal? ' + ( chimp instanceof Animal ) + '\n' +
	'chimp is a carnivore? ' + ( chimp instanceof Carnivore ) + '\n' +
	'chimp is a primate? ' + ( chimp instanceof Primate ) );

Suppose that we have an Mammal model and a Primate model extending Mammal. If we have a Primate object with id 3, this object will be returned when we have a relation pointing to a Mammal with id 3, as Primate is regarded a specific kind of Mammal; it's just a Mammal with possibly some primate-specific properties or methods.

Note that this means that there cannot be any overlap in ids between instances of Mammal and Primate, as the Primate with id 3 will be the Mammal with id 3.

subModelTypeAttributerelationalModel.subModelTypeAttribute

A string. Default: type.

The subModelTypeAttribute references an attribute on the data used to instantiate relatedModel. The attribute that will be checked to determine the type of model that should be built when a raw object of attributes is set as the related value, and if the relatedModel has one or more submodels.

Instance methods

getAsyncrelationalModel.getAsync(attr<string>, [options<object>]

Returns: jQuery.Deferred A jQuery promise

Get an attribute's value asynchronously. If available, the local value will be returned. If attr is a relation and one or more of its models are not available, they will be fetched.

This can be used specifically for lazy-loading scenarios. Only models are referenced in the attributes but have not been found/created yet are fetched. Setting options.refresh to true will fetch all model(s) from the server. In that case, any model that already exists will be updated with the retrieved data. The options object specifies options to be passed to Backbone.Sync.

By default, a separate request will be fired for each model that is to be fetched from the server (if `key` references a collection). However, if your server/API supports it, you can fetch the set of models in one request by specifying a collectionType for the relation you call getAsync on. The collectionType should have an overridden url method that allows it to construct a url for an array of models. See this example or Backbone-tastypie for an example.

getIdsToFetchrelationModel.getIdsToFetch(attr<string|Backbone.Relation>, [refresh<boolean>])

Returns: Array A list of the ids that will be fetched when calling getAsync.

getRelationrelationModel.getRelation(attr<string>)

Returns: Backbone.Relation A single initialized relation on the model.

getRelationsrelationModel.getRelations()

Returns: Backbone.Relation[] The set of initialized relations on the model.

setset(key<string>, value, [options<object>]) or set(attributes<object>, [options<object>])

Returns: Backbone.RelationalModel The model instance.

The set method is overridden so that setting a value on an "relational" attribute will update that relation. This is especially important to keep in mind for HasMany relations (which are backed by a Backbone.Collection). For these, calling set can be thought of as being equivalent to calling update on the collection itself, including how the options are handled.

Additional options for a HasMany relation:

add
Default: true. If true, models specified in the arguments but not yet present in the relation will be added to the relation.
merge
Default: true. If true, existing models will be updated with the given attributes.
remove
Default: true. If true, models present in the relation but not specified in the arguments will be removed.

toJSONrelationModel.toJSON(name<string>)

Returns: Object The JSON representation of the model. See Backbone.Model.toJSON.

The regular toJSON function has been overridden and modified to serialize (nested) relations according to their includeInJSON, keySource, and keyDestination options.

Static methods

setuprelationModel.setup()

Returns: Backbone.RelationalModel.constuctor The type.

Initialize the relations and submodels for the model type. Normally, this happens automatically, but it doesn't if you're using CoffeeScript and using the syntax class MyModel extends Backbone.RelationalModel instead of the JavaScript equivalent of MyModel = Backbone.RelationalModel.extend().

This has advantages in CoffeeScript, but it also means that Backbone.Model.extend will not get called. Instead, CoffeeScript generates piece of code that would normally achieve the same. However, extend is also the method that Backbone-relational overrides to set up relations as you're defining your Backbone.RelationalModel subclass.

In this case, you should call setup manually after defining your subclass CoffeeScript-style. For example:

Note: this is a static method. It operates on the model type itself, not on an instance of it.

class Animal extends Backbone.RelationalModel
    urlRoot: "/animal"

class Mammal extends Animal
    subModelTypes:
        "primate": "Primate"
        "carnivore": "Carnivore"

    relations: [
        # More relations
    ]

Mammal.setup()

class Primate extends Mammal

class Carnivore extends Mammal

chimp = Mammal.build( { id: 3, species: "chimp", type: "primate" } )

buildrelationalModel.build(attributes<object>, [options<object>])

Returns: Backbone.RelationalModel A model instance.

Create an instance of a model, taking into account what submodels have been defined.

Note: this is a static method. It operates on the model type itself, not on an instance.

findOrCreate relationalModel.findOrCreate(attributes<string|number|object>, [options<object>])

Returns: Backbone.RelationalModel A model instance.

Search for a model instance in the Backbone.Relational.store, and return the model if found. A new model will be created if no model is found, attributes is an object, and options.create is true.

Accepted options:

create
Default: true. If true, a new model will be created if an instance matching attributes isn't found in the store.
merge
Default: true. If true, a found model will be updated with attributes (if attributes is an object).
parse
Default: false. If true, attributes will be parsed first. Please note this will cause Model.parse to be called as a function (this will not point to a model), instead of as a method.

Note: this is a static method. It operates on the model type itself, not on an instance of it.

find relationalModel.find(attributes<string|number|object>, [options<object>])

Returns: Backbone.RelationalModel A model instance.

A shortcut for findOrCreate that uses create: false. Accepts the same options as findOrCreate (except for create).

Note: this is a static method. It operates on the model type itself, not on an instance of it.

findModel relationalModel.findModel(attributes<string|number|object>)

Returns: Backbone.RelationalModel A model instance.

A hook to override the matching when updating (or creating) a model. The default implementation is to look up the model by id in the store: return Backbone.Relational.store.find( this, attributes );

Custom behavior is useful in cases where (a collection of) nested data gets saved to the server. Consider saving the following model:

var zoo = new Zoo( { id: 1, name: 'Artis', animals: [
	{ species: 'Giraffe' },
	{ species: 'Camel' }
] } );

alert( JSON.stringify( zoo.toJSON(), null, 4 ) );

Normally, whatever you use as server-side logic will respond by creating two animals, and assigning them an id. The response will be used by Backbone-relational to update existing models. However, updating a model starts by looking up the local model with the same id; and in this case, Backbone-relational does not know which local models corresponds to which created animal with an id. A simple fix in this case would be to add a fallback option for the matching by using the animal's species. Do note you'd want to use a more robust method usually, such as using a new model's cid.

Zoo.findModel = function( attributes ) {
	// Try to find an instance of 'this' model type in the store
	var model = Backbone.Relational.store.find( this, attributes );

	if ( !model && _.isObject( attributes ) ) {
		var coll = Backbone.Relational.store.getCollection( this );

		model = coll.find( function( m ) {
			return m.species === attributes.species;
		});
	}

	return model;
};

Note: this is a static method. It operates on the model type itself, not on an instance of it.

Catalog of Events

Backbone-relational makes a couple of additional events available to you, on top of the events already found in Backbone.

  • An "add" event is triggered on addition to a HasMany relation. Bind to:
    add:<key>function(addedModel<Backbone.Model>, related<Backbone.Collection>)
  • A "remove" event is triggered on removal from a HasMany relation. Bind to:
    remove:<key>function(removedModel<Backbone.Model>, related<Backbone.Collection>)
  • A "change" event is triggered on changes to the contents of both HasOne and HasMany relations. Bind to:
    change:<key>function(model<Backbone.Model>, related<Backbone.Model|Backbone.Collection>)

Backbone.Relation

Each relation definition on a model is used to create in instance of a Backbone.Relation; either a Backbone.HasOne or a Backbone.HasMany.

Backbone.HasOne

Defines a HasOne relation. When defining a reverseRelation, the default type will be HasMany. However, this can also be set to HasOne to define a one-to-one relation.

Backbone.HasMany

Defines a HasMany relation. When defining a reverseRelation, the type will be HasOne.

Backbone.Store

Backbone.Store is a global model cache. Per application, one instance is created (much like Backbone.History), which is accessible as Backbone.Relational.store.

addModelScopeBackbone.Relational.store.addModelScope(scope<object>)

Add a namespace on which models and collections are defined. This is especially useful when working in an environment without a shared global scope (like window is in a browser), where you'll need to tell the store where your models are defined, so it can resolve them to create and maintain relations.

removeModelScopeBackbone.Relational.store.removeModelScope()

Remove a scope. This allows you to remove a scope you added previously, or to remove the default 'global' scope (window in the browser) scope to prevent Backbone-relational from resolving objects on it.

resetBackbone.Relational.store.reset()

Reset the store to its original state. This will disable relations for all models created up to this point, remove added model scopes, and removed all internal store collections.

unregisterBackbone.Relational.store.unregister(type<Backbone.RelationalModel|Backbone.RelationalModel.constructor|Backbone.Collection>)

Unregister a single model or a collection. Unregistering a model will remove a model from any relations it's involved in. Internally, unregister is called when a model has been destroyed. It can also be called explicitly to on models you don't want Backbone-relational to consider for relations anymore, for example to free up models used as (temporary) search results.

Examples

A tutorial by antoviaque, and the accompanying git repository.

A basic working example to get you started:

var paul = new Person({
	id: 'person-1',
	name: 'Paul',
	user: { id: 'user-1', login: 'dude', email: 'me@gmail.com' }
});

// A User object is automatically created from the JSON; so 'login' returns 'dude'.
paul.get('user').get('login');

var ourHouse = new House({
	id: 'house-1',
	location: 'in the middle of the street',
	occupants: ['person-1', 'person-2', 'person-5']
});

// 'ourHouse.occupants' is turned into a Backbone.Collection of Persons.
// The first person in 'ourHouse.occupants' will point to 'paul'.
ourHouse.get('occupants').at(0); // === paul

// If a collection is created from a HasMany relation, it contains a reference
// back to the originator of the relation
ourHouse.get('occupants').livesIn; // === ourHouse

// The `occupants` relation on 'House' has been defined as a HasMany, with a reverse relation
// to `livesIn` on 'Person'. So, 'paul.livesIn' will automatically point back to 'ourHouse'.
paul.get('livesIn'); // === ourHouse

// You can control which relations get serialized to JSON, using the 'includeInJSON'
// property on a Relation. Also, each object will only get serialized once to prevent loops.
alert( JSON.stringify( paul.get('user').toJSON(), null, '\t' ) );
// Load occupants 'person-2' and 'person-5', which don't exist yet, from the server
ourHouse.getAsync( 'occupants' );

// Use the `add` and `remove` events to listen for additions/removals on a HasMany relation.
// Here, we listen for changes to `ourHouse.occupants`.
ourHouse
	.on( 'add:occupants', function( model, coll ) {
		console.log( 'add %o', model );
		// Do something. Create a View?
	})
	.on( 'remove:occupants', function( model, coll ) {
		console.log( 'remove %o', model );
		// Do somehting. Destroy a View?
	});

// Use the 'update' event to listen for changes on a HasOne relation (like 'Person.livesIn').
paul.on( 'change:livesIn', function( model, attr ) {
	console.log( 'change `livesIn` to %o', attr );
});

// Modifying either side of a bi-directional relation updates the other side automatically.
// Take `paul` out or `ourHouse`; this triggers `remove:occupants` on `ourHouse`,
// and `change:livesIn` on `paul`
ourHouse.get( 'occupants' ).remove( paul );

alert( 'paul.livesIn=' + paul.get( 'livesIn' ) );
// Move into `theirHouse`; triggers 'add:occupants' on ourHouse, and 'change:livesIn' on paul
theirHouse = new House( { id: 'house-2' } );
paul.set( { 'livesIn': theirHouse } );

alert( 'theirHouse.occupants=' + theirHouse.get( 'occupants' ).pluck( 'name' ) );

This is achieved using the following relations and models:

House = Backbone.RelationalModel.extend({
	// The 'relations' property, on the House's prototype. Initialized separately for each
	// instance of House. Each relation must define (as a minimum) the 'type', 'key' and
	// 'relatedModel'. Options include 'includeInJSON', 'createModels' and 'reverseRelation'.
	relations: [
		{
			type: Backbone.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'.
			key: 'occupants',
			relatedModel: 'Person',
			includeInJSON: Backbone.Model.prototype.idAttribute,
			collectionType: 'PersonCollection',
			reverseRelation: {
				key: 'livesIn'
			}
		}
	]
});

Person = Backbone.RelationalModel.extend({
	relations: [
		{ // Create a (recursive) one-to-one relationship
			type: Backbone.HasOne,
			key: 'user',
			relatedModel: 'User',
			reverseRelation: {
				type: Backbone.HasOne,
				key: 'person'
			}
		}
	],

	initialize: function() {
		// do whatever you want :)
	}
});

PersonCollection = Backbone.Collection.extend({
	url: function( models ) {
		// Logic to create a url for the whole collection, or a set of models.
		// See the tests, or Backbone-tastypie, for an example.
		return '/person/' + ( models ? 'set/' + _.pluck( models, 'id' ).join(';') + '/' : '' );
	}
});

User = Backbone.RelationalModel.extend();

Change Log

Master (future)diffdownload

0.10.0 (19 August 2015)diffdownload

0.9.0 (25 October 2014)diffdownload

0.8.8 (1 April 2014)diffdownload

0.8.7 (17 January 2014)diffdownload

0.8.6 (16 August 2013)diffdownload

0.8.5 (10 April 2013)diffdownload

0.8.0 5 March 2013diffdownload

0.7.1 17 Januari 2013diffdownload

0.7.0 18 December 2012diffdownload

0.6.0 02 August 2012diffdownload

0.5.0 17 February 2012diffdownload

0.4.0 23 July 2011diffdownload

First commit 11 April 2011commitdownload

The original version of Backbone-relational! This already contained much of the basics: HasOne and HasMany relations (including reverseRelation), Backbone.RelationalModel and Backbone.Store.

Under the Hood

The model Store

Each Backbone.RelationalModel registers itself with Backbone.Relational.Store upon creation, and is removed from the store when destroyed. When creating or updating an attribute that is a key in a relation, removed related objects are notified of their removal, and new related objects are looked up in the Store.

Backbone-relational only allows the existence of one model instance for each model type id. This check is there to enforce there will only be one version of a model with a certain id at any given time (which is also the reason for the existence of Backbone.Relational.Store). This is necessary to enforce consistency and integrity of relations.

If multiple versions were allowed, inadvertently manipulating or performing a save or destroy on another version of that model (which is still around on the client, and can for example still be bound to one or more views in your application, either on purpose or inadvertently) would save its state to the server, killing its relations, and the server response would set the same (incorrect) data on the 'current' version of the model on the client. By then, you'd be in trouble.

Therefore, Backbone-relational simply does not allow this situation to occur. This is much safer than putting the burden on the developer to always make sure every older version of a model is completely decoupled from every other part of your application. It might be annoying to get an error every now and then, and sometimes inconvenient to have to use the factory method findOrCreate, but it's much better than subtle bugs that can lead to major data loss later on in the life cycle of your application.

Event queuing

Most of Backbone's default events are queued by Backbone-relational. This can complicate debugging since it 'breaks' the call stack, but is a necessary part of the abstraction offered by it.

The event queuing kicks in every time (nested) relations need to be updated as the result of calling a Backbone method that modifies a model's attributes: on creation, and on set, unset, and clear.

The basic problem is that when manipulating relations, you only want the events to fire once ALL relations have been updated; also those on models one, two, or more relations away. For example, when you have an event listener on add, you want to be able to use the model you receive as the first argument and its relations fully instead of getting raw JS objects:

var p = new Person( { id: 'p1', name: 'Larry Page' } );

p.on( 'add:jobs', function( job ) {
	// Here, you want the correct person and company to be set on job, instead of plain js.
	alert( job.get( 'person' ).get( 'name' ) + ' @ ' + job.get( 'company' ).get( 'name' ) );
});

p.get( 'jobs' ).add( { company: { name: 'Google' }, person: p.id } );

To achieve this, Backbone's events are prevented from firing immediately when add is called, but are delayed until the all (nested) relations have reached a stable state again. Events are then fired at the first available opportunity; as soon as the last model updating its relations unblocks the Backbone.Relational.eventQueue.