backbone-relational.js revision 89092dc10fe08b037266c0b4efb94b221f6fffb3
/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */
/**
* Backbone-relational.js 0.9.0
* (c) 2011-2014 Paul Uithol and contributors (https://github.com/PaulUithol/Backbone-relational/graphs/contributors)
*
* Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
* For details and documentation: https://github.com/PaulUithol/Backbone-relational.
* Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
*
* Example:
*
Zoo = Backbone.RelationalModel.extend({
relations: [ {
type: Backbone.HasMany,
key: 'animals',
relatedModel: 'Animal',
reverseRelation: {
key: 'livesIn',
includeInJSON: 'id'
// 'relatedModel' is automatically set to 'Zoo'; the 'relationType' to 'HasOne'.
}
} ],
toString: function() {
return this.get( 'name' );
}
});
Animal = Backbone.RelationalModel.extend({
toString: function() {
return this.get( 'species' );
}
});
// Creating the zoo will give it a collection with one animal in it: the monkey.
// The animal created after that has a relation `livesIn` that points to the zoo it's currently associated with.
// If you instantiate (or fetch) the zebra later, it will automatically be added.
var zoo = new Zoo({
name: 'Artis',
animals: [ { id: 'monkey-1', species: 'Chimp' }, 'lion-1', 'zebra-1' ]
});
var lion = new Animal( { id: 'lion-1', species: 'Lion' } ),
monkey = zoo.get( 'animals' ).first(),
sameZoo = lion.get( 'livesIn' );
*/
// Set up Backbone-relational for the environment. Start with AMD.
}
// Next for Node.js or CommonJS.
else if ( typeof exports !== 'undefined' ) {
}
// Finally, as a browser global. Use `root` here as it references `window`.
else {
}
"use strict";
Backbone.Relational = {
showWarnings: true
};
/**
* Semaphore mixin; can be used as both binary and counting.
**/
_permitsAvailable: null,
_permitsUsed: 0,
acquire: function() {
throw new Error( 'Max permits acquired' );
}
else {
this._permitsUsed++;
}
},
release: function() {
if ( this._permitsUsed === 0 ) {
throw new Error( 'All permits released' );
}
else {
this._permitsUsed--;
}
},
isLocked: function() {
return this._permitsUsed > 0;
},
setAvailablePermits: function( amount ) {
if ( this._permitsUsed > amount ) {
throw new Error( 'Available permits cannot be less than used permits' );
}
this._permitsAvailable = amount;
}
};
/**
* A BlockingQueue that accumulates items while blocked (via 'block'),
* and processes them when unblocked (via 'unblock').
* Process can also be called manually (via 'process').
*/
Backbone.BlockingQueue = function() {
this._queue = [];
};
_queue: null,
if ( this.isBlocked() ) {
}
else {
func();
}
},
// Some of the queued events may trigger other blocking events. By
// copying the queue here it allows queued events to process closer to
// the natural order.
//
// queue events [ 'A', 'B', 'C' ]
// A handler of 'B' triggers 'D' and 'E'
// By copying `this._queue` this executes:
// [ 'A', 'B', 'D', 'E', 'C' ]
// The same order the would have executed if they didn't have to be
// delayed and queued.
process: function() {
this._queue = [];
}
},
block: function() {
this.acquire();
},
unblock: function() {
this.release();
if ( !this.isBlocked() ) {
this.process();
}
},
isBlocked: function() {
return this.isLocked();
}
});
/**
* Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'change:<key>')
* until the top-level object is fully initialized (see 'Backbone.RelationalModel').
*/
/**
* Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel.
* Handles lookup for relations.
*/
this._collections = [];
this._reverseRelations = [];
this._orphanRelations = [];
this._subModels = [];
this._modelScopes = [ exports ];
};
/**
* Create a new `Relation`.
* @param {Backbone.RelationalModel} [model]
* @param {Object} relation
* @param {Object} [options]
*/
var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type );
var rel = new type( model, relation, options ); // Also pushes the new Relation into `model._relations`
}
else {
Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation );
}
},
/**
* Add a scope for `getObjectByName` to look for model types by name.
* @param {Object} scope
*/
addModelScope: function( scope ) {
},
/**
* Remove a scope.
* @param {Object} scope
*/
removeModelScope: function( scope ) {
},
/**
* Add a set of subModelTypes to the store, that can be used to resolve the '_superModel'
* for a model later in 'setupSuperModel'.
*
* @param {Backbone.RelationalModel} subModelTypes
* @param {Backbone.RelationalModel} superModelType
*/
this._subModels.push({
'superModelType': superModelType,
'subModels': subModelTypes
});
},
/**
* Check if the given modelType is registered as another model's subModel. If so, add it to the super model's
* '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'.
*
* @param {Backbone.RelationalModel} modelType
*/
setupSuperModel: function( modelType ) {
if ( modelType === subModelType ) {
// Set 'modelType' as a child of the found superModel
// Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'.
return true;
}
}, this ).length;
}, this );
},
/**
* Add a reverse relation. Is added to the 'relations' property on model's prototype, and to
* existing instances of 'model' in the store as well.
* @param {Object} relation
* @param {Backbone.RelationalModel} relation.model
* @param {String} relation.type
* @param {String} relation.key
* @param {String|Object} relation.relatedModel
*/
addReverseRelation: function( relation ) {
});
});
this.retroFitRelation( relation );
}
},
/**
* Deposit a `relation` for which the `relatedModel` can't be resolved at the moment.
*
* @param {Object} relation
*/
addOrphanRelation: function( relation ) {
});
});
}
},
/**
* Try to initialize any `_orphanRelation`s
*/
processOrphanRelations: function() {
// Make sure to operate on a copy since we're removing while iterating
if ( relatedModel ) {
this.initializeRelation( null, rel );
}
}, this );
},
/**
*
* @param {Backbone.RelationalModel.constructor} type
* @param {Object} relation
* @private
*/
}
}, this );
},
/**
* Add a 'relation' to all existing instances of 'relation.model' in the store
* @param {Object} relation
*/
retroFitRelation: function( relation ) {
return;
}
}, this );
},
/**
* Find the Store's collection for a certain type of model.
* @param {Backbone.RelationalModel} type
* @param {Boolean} [create=true] Should a collection be created if none is found?
* @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
*/
}
while ( rootModel._superModel ) {
}
});
}
return coll;
},
/**
* Find a model type on one of the modelScopes by name. Names are split on dots.
* @param {String} name
* @return {Object}
*/
getObjectByName: function( name ) {
type = null;
}, scope );
return true;
}
}, this );
return type;
},
_createCollection: function( type ) {
var coll;
// If 'type' is an instance, take its constructor
}
// Type should inherit from Backbone.RelationalModel.
}
return coll;
},
/**
* Find the attribute that is to be used as the `id` on a given object
* @param type
* @param {String|Number|Object|Backbone.RelationalModel} item
* @return {String|Number}
*/
if ( id === null ) {
}
}
}
// Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179')
id = null;
}
return id;
},
/**
* Find a specific model of a certain `type` in the store
* @param type
* @param {String|Number|Object|Backbone.RelationalModel} item
*/
// Because the found object could be of any of the type's superModel
// types, only return it if it's actually of the type asked for.
if ( coll ) {
return obj;
}
}
return null;
},
/**
* Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'.
* @param {Backbone.RelationalModel} model
*/
if ( coll ) {
}
},
/**
* Check if the given model may use the given `id`
* @param model
* @param [id]
*/
}
throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" );
}
},
/**
* Explicitly update a model's id in its store collection
* @param {Backbone.RelationalModel} model
*/
// Register a model if it isn't yet (which happens if it was created without an id).
}
// This triggers updating the lookup indices kept in a collection
// Trigger an event on model so related models (having the model's new id in their keyContents) can add it.
},
/**
* Unregister from the store: a specific model, a collection, or a model type.
* @param {Backbone.RelationalModel|Backbone.RelationalModel.constructor|Backbone.Collection} type
*/
unregister: function( type ) {
var coll,
}
}
else {
}
this.stopListening( model );
}, this );
// If we've unregistered an entire store collection, reset the collection (which is much faster).
// Otherwise, remove each model one by one.
}
else {
}
else {
}
}, this );
}
},
/**
* Reset the `store` to it's original state. The `reverseRelations` are kept though, since attempting to
* re-initialize these on models would lead to a large amount of warnings.
*/
reset: function() {
this.stopListening();
// Unregister each collection to remove event listeners
this.unregister( coll );
}, this );
this._collections = [];
this._subModels = [];
this._modelScopes = [ exports ];
}
});
/**
* The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events
* are used to regulate addition and removal of models from relations.
*
* @param {Backbone.RelationalModel} [instance] Model that this relation is created for. If no model is supplied,
* Relation just tries to instantiate it's `reverseRelation` if specified, and bails out after that.
* @param {Object} options
* @param {string} options.key
* @param {Backbone.RelationalModel.constructor} options.relatedModel
* @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids.
* @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store.
* @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate
* the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs
* {Backbone.Relation|String} type ('HasOne' or 'HasMany').
* @param {Object} opts
*/
// Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype
Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type );
// No 'relatedModel' is interpreted as self-referential
if ( _.isUndefined( this.relatedModel ) ) {
this.relatedModel = this.model;
}
// Otherwise, try to resolve the given value to an object
if ( _.isFunction( this.relatedModel ) && !( this.relatedModel.prototype instanceof Backbone.RelationalModel ) ) {
}
if ( _.isString( this.relatedModel ) ) {
}
if ( !this.checkPreconditions() ) {
return;
}
// Add the reverse relation on 'relatedModel' to the store's reverseRelations
isAutoRelation: true,
model: this.relatedModel,
relatedModel: this.model,
reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation
},
this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
) );
}
if ( instance ) {
var contentKey = this.keySource;
contentKey = this.key;
}
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
}
// Add this Relation to instance._relations
this.initialize( opts );
this.instance.getAsync( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} );
}
// When 'relatedModel' are created or destroyed, check if it affects this relation.
}
};
// Fix inheritance :\
// Set up all inheritable **Backbone.Relation** properties and methods.
options: {
createModels: true,
includeInJSON: true,
isAutoRelation: false,
autoFetch: false,
parse: false
},
instance: null,
key: null,
keyContents: null,
relatedModel: null,
relatedCollection: null,
reverseRelation: null,
related: null,
/**
* Check several pre-conditions.
* @return {Boolean} True if pre-conditions are satisfied, false if they're not.
*/
checkPreconditions: function() {
var i = this.instance,
k = this.key,
m = this.model,
rm = this.relatedModel,
if ( !m || !k || !rm ) {
warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm );
return false;
}
// Check if the type in 'model' inherits from Backbone.RelationalModel
warn && console.warn( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).', this, i );
return false;
}
// Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).', this, rm );
return false;
}
// Check if this is not a HasMany, and the reverse relation is HasMany as well
warn && console.warn( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.', this );
return false;
}
// Check if we're not attempting to create a relationship on a `key` that's already used.
}, this );
if ( existing ) {
warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.',
this, k, i, existing );
return false;
}
}
return true;
},
/**
* Set the related model(s) for this relation
* @param {Backbone.Model|Backbone.Collection} related
*/
setRelated: function( related ) {
},
/**
* Determine if a relation (on a different RelationalModel) is the reverse
* relation of the current one.
* @param {Backbone.Relation} relation
* @return {Boolean}
*/
_isReverseRelation: function( relation ) {
return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
},
/**
* Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
* @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model.
* If not specified, 'this.related' is used.
* @return {Backbone.Relation[]}
*/
getReverseRelations: function( model ) {
var reverseRelations = [];
// Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array.
var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] ),
relations = null,
relation = null;
if ( this._isReverseRelation( relation ) ) {
}
}
}
return reverseRelations;
},
/**
* When `this.instance` is destroyed, cleanup our relations.
* Get reverse relation, call removeRelated on each.
*/
destroy: function() {
this.stopListening();
this.setRelated( null );
}
this.setRelated( this._prepareCollection() );
}
}, this );
}
});
options: {
},
initialize: function( opts ) {
this.setRelated( related );
// Notify new 'related' object of the new relation.
}, this );
},
/**
* Find related Models.
* @param {Object} [options]
* @return {Backbone.Model}
*/
findRelated: function( options ) {
var related = null;
if ( this.keyContents instanceof this.relatedModel ) {
related = this.keyContents;
}
}
// Nullify `keyId` if we have a related model; in case it was already part of the relation
if ( related ) {
this.keyId = null;
}
return related;
},
/**
* Normalize and reduce `keyContents` to an `id`, for easier comparison
* @param {String|Number|Backbone.Model} keyContents
*/
setKeyContents: function( keyContents ) {
this.keyContents = keyContents;
},
/**
* Event handler for `change:<key>`.
* If the key is changed, notify old & new reverse relations and initialize the new relation.
*/
// Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
if ( this.isLocked() ) {
return;
}
this.acquire();
// 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change
// is the result of a call from a relation. If it's not, the change is the result of
// a 'set' call on this.instance.
if ( changed ) {
this.setKeyContents( attr );
this.setRelated( related );
}
// Notify old 'related' object of the terminated relation
}, this );
}
// Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
// that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
// In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
}, this );
// Fire the 'change:<key>' event if 'related' was updated
var dit = this;
this.changed = true;
});
}
this.release();
},
/**
* If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
*/
if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well
this.keyId = null;
}
},
// Allow 'model' to set up its relations before proceeding.
// (which can result in a call to 'addRelated' from a relation of 'model')
var dit = this;
}
});
},
if ( !this.related ) {
return;
}
var oldRelated = this.related || null;
this.setRelated( null );
}
}
});
collectionType: null,
options: {
collectionKey: true,
},
initialize: function( opts ) {
// Handle a custom 'collectionType'
if ( _.isFunction( this.collectionType ) && this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) {
}
if ( _.isString( this.collectionType ) ) {
}
if ( this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) {
throw new Error( '`collectionType` must inherit from Backbone.Collection' );
}
this.setRelated( related );
},
/**
* Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany.
* If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option.
* @param {Backbone.Collection} [collection]
* @return {Backbone.Collection}
*/
_prepareCollection: function( collection ) {
if ( this.related ) {
this.stopListening( this.related );
}
}
if ( this.options.collectionKey ) {
var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey;
console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey );
}
}
else if ( key ) {
}
}
return collection;
},
/**
* Find related Models.
* @param {Object} [options]
* @return {Backbone.Collection}
*/
findRelated: function( options ) {
var related = null;
// Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection
this._prepareCollection( this.keyContents );
related = this.keyContents;
}
// Otherwise, 'this.keyContents' should be an array of related object ids.
// Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection.
else {
var toAdd = [];
var model = null;
if ( attributes instanceof this.relatedModel ) {
model = attributes;
}
else {
// If `merge` is true, update models here, instead of during update.
);
}
}, this );
}
else {
related = this._prepareCollection();
}
// By now, both `merge` and `parse` will already have been executed for models if they were specified.
// Disable them to prevent additional calls.
}
// Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged')
return related;
},
/**
* Normalize and reduce `keyContents` to a list of `ids`, for easier comparison
* @param {String|Number|String[]|Number[]|Backbone.Collection} keyContents
*/
setKeyContents: function( keyContents ) {
this.keyIds = [];
if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well
}
}, this );
}
},
/**
* Event handler for `change:<key>`.
* If the contents of the key are changed, notify old & new reverse relations and initialize the new relation.
*/
this.setKeyContents( attr );
this.changed = false;
this.setRelated( related );
var dit = this;
// The `changed` flag can be set in `handleAddition` or `handleRemoval`
}
});
}
},
/**
* When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations.
* (should be 'HasOne', must set 'this.instance' as their related).
*/
//console.debug('handleAddition called; args=%o', arguments);
this.changed = true;
}, this );
// Only trigger 'add' once the newly added model is initialized (so, has its relations set up)
var dit = this;
});
},
/**
* When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations.
* (should be 'HasOne', which should be nullified)
*/
//console.debug('handleRemoval called; args=%o', arguments);
this.changed = true;
}, this );
var dit = this;
});
},
var dit = this;
});
},
if ( item ) {
}
},
// Allow 'model' to set up its relations before proceeding.
// (which can result in a call to 'addRelated' from a relation of 'model')
var dit = this;
}
});
},
}
}
});
/**
* A type of Backbone.Model that also maintains relations to other models and collections.
* New events when compared to the original:
* - 'add:<key>' (model, related collection, options)
* - 'remove:<key>' (model, related collection, options)
* - 'change:<key>' (model, related model or collection, options)
*/
relations: null, // Relation descriptions on the prototype
_relations: null, // Relation instances
_isInitialized: false,
_deferProcessing: false,
_queue: null,
_attributeChangeFired: false, // Keeps track of `change` event firing under some conditions (like nested `set`s)
subModelTypeAttribute: 'type',
subModelTypes: null,
// Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'.
// Defer 'processQueue', so that when 'Relation.createModels' is used we trigger 'HasMany'
// collection events only after the model is really fully set up.
// Example: event for "p.on( 'add:jobs' )" -> "p.get('jobs').add( { company: c.id, person: p.id } )".
var dit = this,
// Prevent `collection` from cascading down to nested models; they shouldn't go into this `if` clause.
delete options.collection;
this._deferProcessing = true;
var processQueue = function( model ) {
dit._deferProcessing = false;
dit.processQueue();
}
};
// So we do process the queue eventually, regardless of whether this model actually gets added to 'options.collection'.
_.defer( function() {
processQueue( dit );
});
}
Backbone.Relational.store.listenTo( this, 'relational:unregister', Backbone.Relational.store.unregister );
try {
}
finally {
// Try to run the global queue holding external events
}
},
/**
* Override 'trigger' to queue 'change' and 'change:*' events
*/
var dit = this,
// If we're not in a more complicated nested scenario, fire the change event right away
}
else {
// Determine if the `change` event is still valid, now that all relations are populated
var changed = true;
if ( eventName === 'change' ) {
// `hasChanged` may have gotten reset by nested calls to `set`.
dit._attributeChangeFired = false;
}
else {
if ( rel ) {
// If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`.
// These take precedence over `change:attr` events triggered by `Model.set`.
// The relation sets a fourth attribute to `true`. If this attribute is present,
// continue triggering this event; otherwise, it's from `Model.set` and should be stopped.
// If this event was triggered by a relation, set the right value in `this.changed`
// (a Collection or Model instead of raw data).
if ( changed ) {
}
// Otherwise, this event is from `Model.set`. If the relation doesn't report a change,
// remove attr from `dit.changed` so `hasChanged` doesn't take it into account.
}
}
else if ( changed ) {
dit._attributeChangeFired = true;
}
}
});
}
}
else if ( eventName === 'destroy' ) {
}
else {
}
return this;
},
/**
* Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
* Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
*/
initializeRelations: function( options ) {
this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
this._relations = {};
}, this );
this._isInitialized = true;
this.release();
this.processQueue();
},
/**
* When new values are set, notify this model's relations (also if options.silent is set).
* (called from `set`; Relation.setRelated locks this model before calling 'set' on it to prevent loops)
* @param {Object} [changedAttrs]
* @param {Object} [options]
*/
if ( this._isInitialized && !this.isLocked() ) {
// Fetch data in `rel.keySource` if data got set in there, or `rel.key` otherwise
// Update a relation if its value differs from this model's attributes, or it's been explicitly nullified.
// Which can also happen before the originally intended related model has been found (`val` is null).
}
}
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
}
}, this );
}
},
/**
* Either add to the queue (if we're not initialized yet), or execute right away.
*/
},
/**
* Process _queue
*/
processQueue: function() {
}
},
/**
* Get a specific relation.
* @param {string} attr The relation key to look for.
* @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'attr', or null.
*/
getRelation: function( attr ) {
return this._relations[ attr ];
},
/**
* Get all of the created relations.
* @return {Backbone.Relation[]}
*/
getRelations: function() {
return _.values( this._relations );
},
/**
* Get a list of ids that will be fetched on a call to `getAsync`.
* @param {string|Backbone.Relation} attr The relation key to fetch models for.
* @param [refresh=false] Add ids for models that are already in the relation, refreshing them?
* @return {Array} An array of ids that need to be fetched.
*/
ids = rel ? ( rel.keyIds && rel.keyIds.slice( 0 ) ) || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) : [];
// On `refresh`, add the ids for current models in the relation to `idsToFetch`
if ( refresh ) {
}
});
}
return ids;
},
/**
* Get related objects. Returns a single promise, which can either resolve immediately (if the related model[s])
* are already present locally, or after fetching the contents of the requested attribute.
* @param {string} attr The relation key to fetch models for.
* @param {Object} [options] Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
* @param {Boolean} [options.refresh=false] Fetch existing models from the server as well (in order to update them).
* @return {jQuery.Deferred} A jQuery promise object. When resolved, its `done` callback will be called with
* contents of `attr`.
*/
// Set default `options` for fetch
var dit = this,
requests = [],
var models = [],
createdModels = [],
createModels = function() {
// Find (or create) a model for each one that is to be fetched
if ( !model ) {
var attrs = {};
}
return model;
}, this );
};
// Try if the 'collection' can provide a url to fetch a set of models in one request.
// This assumes that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
// To make sure it can, test if the url we got by supplying a list of models to fetch is different from
// the one supplied for the default fetch action (without args to 'url').
if ( setUrl === defaultUrl ) {
createModels();
if ( setUrl === defaultUrl ) {
setUrl = null;
}
}
}
if ( setUrl ) {
// Do a single request to fetch all models
{
error: function() {
});
},
},
);
}
else {
// Make a request per model to fetch
createModels();
}
{
error: function() {
}
}
},
);
}, this );
}
}
function() {
}
);
},
// Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object
var attributes,
attributes = key;
}
else {
attributes = {};
}
try {
// Check if we're not setting a duplicate id before actually calling `set`.
// Ideal place to set up relations, if this is the first time we're here for this model
if ( !this._isInitialized && !this.isLocked() ) {
this.constructor.initializeModelHierarchy();
}
this.initializeRelations( options );
}
// The store should know about an `id` update asap
}
if ( attributes ) {
}
}
finally {
// Try to run the global queue holding external events
}
return result;
},
clone: function() {
attributes[ this.idAttribute ] = null;
}
});
return new this.constructor( attributes );
},
/**
* Convert relations to JSON, omits them when required
*/
// If this Model has already been fully serialized in this branch once, return to avoid loops
if ( this.isLocked() ) {
return this.id;
}
this.acquire();
}
value = null;
if ( includeInJSON === true ) {
}
}
else if ( _.isString( includeInJSON ) ) {
}
}
// Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute`
}
}
}
}
}
else if ( _.isArray( includeInJSON ) ) {
value = [];
var curJson = {};
});
});
}
value = {};
});
}
}
else {
}
// In case of `wait: true`, Backbone will simply push whatever's passed into `save` into attributes.
// We'll want to get this information into the JSON, even if it doesn't conform to our normal
// expectations of what's contained in it (no model/collection for a relation, etc).
}
if ( includeInJSON ) {
}
}
});
this.release();
return json;
}
},
{
/**
*
* @param superModel
* @returns {Backbone.RelationalModel.constructor}
*/
setup: function( superModel ) {
// We don't want to share a relations array with a parent, as this will cause problems with reverse
// relations. Since `relations` may also be a property or function, only use slice if we have an array.
this._subModels = {};
this._superModel = null;
// If this model has 'subModelTypes' itself, remember them in the store
}
// The 'subModelTypes' property should not be inherited, so reset it.
else {
this.prototype.subModelTypes = null;
}
// Initialize all reverseRelations that belong to this new model.
}
var preInitialize = true;
/**
* The related model might not be defined for two reasons
* 1. it is related to itself
* 2. it never gets defined, e.g. a typo
* 3. the model hasn't been defined yet, but will be later
* In neither of these cases do we need to pre-initialize reverse relations.
* However, for 3. (which is, to us, indistinguishable from 2.), we do need to attempt
* setting up this relation again later, in case the related model is defined later.
*/
}
if ( preInitialize ) {
}
}
}
}, this );
return this;
},
/**
* Create a 'Backbone.Model' instance based on 'attributes'.
* @param {Object} attributes
* @param {Object} [options]
* @return {Backbone.Model}
*/
// 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet.
this.initializeModelHierarchy();
// Determine what type of (sub)model should be built if applicable.
},
/**
* Determines what type of (sub)model should be built if applicable.
* Looks up the proper subModelType in 'this._subModels', recursing into
* types until a match is found. Returns the applicable 'Backbone.Model'
* or null if no match is found.
* @param {Backbone.Model} type
* @param {Object} attributes
* @return {Backbone.Model}
*/
if ( subModelType ) {
return subModelType;
}
else {
// Recurse into subModelTypes to find a match
if ( subModelType ) {
return subModelType;
}
}
}
}
return null;
},
/**
*
*/
initializeModelHierarchy: function() {
// Inherit any relations that have been defined in the parent model.
this.inheritRelations();
// If we came here through 'build' for a model that has 'subModelTypes' then try to initialize the ones that
// haven't been resolved yet.
if ( this.prototype.subModelTypes ) {
});
}
},
inheritRelations: function() {
// Bail out if we've been here before.
return;
}
// Try to initialize the _superModel.
// If a superModel has been found, copy relations from the _superModel if they haven't been inherited automatically
// (due to a redefinition of 'relations').
if ( this._superModel ) {
// The _superModel needs a chance to initialize its own inherited relations before we attempt to inherit relations
// from the _superModel. You don't want to call 'initializeModelHierarchy' because that could cause sub-models of
// this class to inherit their relations before this class has had chance to inherit it's relations.
this._superModel.inheritRelations();
// Find relations that exist on the '_superModel', but not yet on this model.
var inheritedRelations = _.filter( this._superModel.prototype.relations || [], function( superRel ) {
}, this );
}, this );
}
}
// Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail the
// isUndefined/isNull check next time.
else {
this._superModel = false;
}
},
/**
* Find an instance of `this` type in 'Backbone.Relational.store'.
* A new model is created if no matching model is found, `attributes` is an object, and `options.create` is true.
* - If `attributes` is a string or a number, `findOrCreate` will query the `store` and return a model if found.
* - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.merge` is `false`.
* @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
* @param {Object} [options]
* @param {Boolean} [options.create=true]
* @param {Boolean} [options.merge=true]
* @param {Boolean} [options.parse=false]
* @return {Backbone.RelationalModel}
*/
// If specified, use a custom `find` function to match up existing models to the given attributes.
// Otherwise, try to find an instance of 'this' model type in the store
// If we found an instance, update it with the data in 'item' (unless 'options.merge' is false).
// If not, create an instance (unless 'options.create' is false).
if ( _.isObject( attributes ) ) {
// Make sure `options.collection` and `options.url` doesn't cascade to nested models
delete options.collection;
}
}
}
return model;
},
/**
* Find an instance of `this` type in 'Backbone.Relational.store'.
* - If `attributes` is a string or a number, `find` will query the `store` and return a model if found.
* - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.merge` is `false`.
* @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
* @param {Object} [options]
* @param {Boolean} [options.merge=true]
* @param {Boolean} [options.parse=false]
* @return {Backbone.RelationalModel}
*/
},
/**
* 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.
* @param {Object} attributes
* @returns {Backbone.RelationalModel}
*/
findModel: function( attributes ) {
}
});
/**
* Override Backbone.Collection._prepareModel, so objects will be built using the correct type
* if the collection.model has subModels.
* Attempts to find a model for `attrs` in Backbone.store through `findOrCreate`
* (which sets the new properties on it if found), or instantiates a new model.
*/
var model;
if ( !attrs.collection ) {
attrs.collection = this;
}
}
else {
options.collection = this;
}
else {
}
model = false;
}
}
return model;
};
/**
* Override Backbone.Collection.set, so we'll create objects from attributes where required,
* and update the existing models. Also, trigger 'relational:add'.
*/
// Short-circuit if this Collection doesn't hold RelationalModels
}
}
newModels = [],
toAdd = [],
model = null;
//console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options );
}
if ( model ) {
}
// If we arrive in `add` while performing a `set` (after a create, so the model gains an `id`),
// we may get here before `_onModelEvent` has had the chance to update `_byId`.
}
}
}
// Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc).
// If `parse` was specified, the collection and contained models have been parsed now.
// Fire a `relational:add` event for any model in `newModels` that has actually been added to the collection.
}
}
return result;
};
/**
* Override 'Backbone.Collection.remove' to trigger 'relational:remove'.
*/
// Short-circuit if this Collection doesn't hold RelationalModels
}
toRemove = [];
//console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options );
}, this );
var result = remove.call( this, singular ? ( toRemove.length ? toRemove[ 0 ] : null ) : toRemove, options );
}, this );
return result;
};
/**
* Override 'Backbone.Collection.reset' to trigger 'relational:reset'.
*/
}
return result;
};
/**
* Override 'Backbone.Collection.sort' to trigger 'relational:reset'.
*/
}
return result;
};
/**
* Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations
* are ready.
*/
// Short-circuit if this Collection doesn't hold RelationalModels
}
if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' || eventName === 'sort' ) {
var dit = this,
// the fourth argument is the option object.
// we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked
}
});
}
else {
}
return this;
};
// Override .extend() to automatically call .setup()
return child;
};
}));