# HG changeset patch # User veltr # Date 1366723400 -7200 # Node ID 1615c7e4ef9d041d9227946ef39a0f8d8cf64e9f # Parent c472984db275f7795d4ee6c599727e27b69ebcb3 Updated Renkan4Metadataplayer diff -r c472984db275 -r 1615c7e4ef9d src/js/defaults.js --- a/src/js/defaults.js Wed Apr 03 15:44:17 2013 +0200 +++ b/src/js/defaults.js Tue Apr 23 15:23:20 2013 +0200 @@ -21,7 +21,7 @@ backboneRelational: "backbone-relational.js", paper: "paper.js", jqueryMousewheel: "jquery.mousewheel.min.js", - renkanPublish: "renkan-publish.js", + renkanPublish: "renkan.js", processing: "processing-1.3.6.min.js", recordMicSwf: "record_mic.swf" }, diff -r c472984db275 -r 1615c7e4ef9d src/js/libs/backbone-relational.js --- a/src/js/libs/backbone-relational.js Wed Apr 03 15:44:17 2013 +0200 +++ b/src/js/libs/backbone-relational.js Tue Apr 23 15:23:20 2013 +0200 @@ -1,6 +1,7 @@ +/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */ /** - * Backbone-relational.js 0.6.0 - * (c) 2011 Paul Uithol + * Backbone-relational.js 0.8.5 + * (c) 2011-2013 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. @@ -8,7 +9,7 @@ */ ( function( undefined ) { "use strict"; - + /** * CommonJS shim **/ @@ -34,7 +35,7 @@ Backbone.Semaphore = { _permitsAvailable: null, _permitsUsed: 0, - + acquire: function() { if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) { throw new Error( 'Max permits acquired' ); @@ -43,7 +44,7 @@ this._permitsUsed++; } }, - + release: function() { if ( this._permitsUsed === 0 ) { throw new Error( 'All permits released' ); @@ -52,11 +53,11 @@ 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' ); @@ -64,7 +65,7 @@ this._permitsAvailable = amount; } }; - + /** * A BlockingQueue that accumulates items while blocked (via 'block'), * and processes them when unblocked (via 'unblock'). @@ -75,7 +76,7 @@ }; _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, { _queue: null, - + add: function( func ) { if ( this.isBlocked() ) { this._queue.push( func ); @@ -84,34 +85,34 @@ func(); } }, - + process: function() { while ( this._queue && this._queue.length ) { this._queue.shift()(); } }, - + 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:', 'remove:' and 'update:') + * Global event queue. Accumulates external events ('add:', 'remove:' and 'change:') * until the top-level object is fully initialized (see 'Backbone.RelationalModel'). */ Backbone.Relational.eventQueue = new Backbone.BlockingQueue(); - + /** * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel. * Handles lookup for relations. @@ -119,15 +120,44 @@ Backbone.Store = function() { this._collections = []; this._reverseRelations = []; + this._orphanRelations = []; this._subModels = []; this._modelScopes = [ exports ]; }; _.extend( Backbone.Store.prototype, Backbone.Events, { + /** + * Create a new `Relation`. + * @param {Backbone.RelationalModel} [model] + * @param {Object} relation + * @param {Object} [options] + */ + initializeRelation: function( model, relation, options ) { + var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type ); + if ( type && type.prototype instanceof Backbone.Relation ) { + 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 ) { this._modelScopes.push( scope ); }, /** + * Remove a scope. + * @param {Object} scope + */ + removeModelScope: function( scope ) { + this._modelScopes = _.without( this._modelScopes, scope ); + }, + + /** * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel' * for a model later in 'setupSuperModel'. * @@ -149,7 +179,7 @@ */ setupSuperModel: function( modelType ) { _.find( this._subModels, function( subModelDef ) { - return _.find( subModelDef.subModels, function( subModelTypeName, typeValue ) { + return _.find( subModelDef.subModels || [], function( subModelTypeName, typeValue ) { var subModelType = this.getObjectByName( subModelTypeName ); if ( modelType === subModelType ) { @@ -165,7 +195,7 @@ }, this ); }, 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. @@ -177,74 +207,108 @@ */ addReverseRelation: function( relation ) { var exists = _.any( this._reverseRelations, function( rel ) { - return _.all( relation, function( val, key ) { - return val === rel[ key ]; - }); + return _.all( relation || [], function( val, key ) { + return val === rel[ key ]; }); + }); if ( !exists && relation.model && relation.type ) { this._reverseRelations.push( relation ); - - var addRelation = function( model, relation ) { - if ( !model.prototype.relations ) { - model.prototype.relations = []; - } - model.prototype.relations.push( relation ); - - _.each( model._subModels, function( subModel ) { - addRelation( subModel, relation ); - }, this ); - }; - - addRelation( relation.model, relation ); - + this._addRelation( relation.model, relation ); this.retroFitRelation( relation ); } }, - + + /** + * Deposit a `relation` for which the `relatedModel` can't be resolved at the moment. + * + * @param {Object} relation + */ + addOrphanRelation: function( relation ) { + var exists = _.any( this._orphanRelations, function( rel ) { + return _.all( relation || [], function( val, key ) { + return val === rel[ key ]; + }); + }); + + if ( !exists && relation.model && relation.type ) { + this._orphanRelations.push( relation ); + } + }, + + /** + * Try to initialize any `_orphanRelation`s + */ + processOrphanRelations: function() { + // Make sure to operate on a copy since we're removing while iterating + _.each( this._orphanRelations.slice( 0 ), function( rel ) { + var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); + if ( relatedModel ) { + this.initializeRelation( null, rel ); + this._orphanRelations = _.without( this._orphanRelations, rel ); + } + }, this ); + }, + + /** + * + * @param {Backbone.RelationalModel.constructor} type + * @param {Object} relation + * @private + */ + _addRelation: function( type, relation ) { + if ( !type.prototype.relations ) { + type.prototype.relations = []; + } + type.prototype.relations.push( relation ); + + _.each( type._subModels || [], function( subModel ) { + this._addRelation( subModel, relation ); + }, this ); + }, + /** * Add a 'relation' to all existing instances of 'relation.model' in the store * @param {Object} relation */ retroFitRelation: function( relation ) { - var coll = this.getCollection( relation.model ); - coll.each( function( model ) { + var coll = this.getCollection( relation.model, false ); + coll && coll.each( function( model ) { if ( !( model instanceof relation.model ) ) { return; } new relation.type( model, relation ); - }, this); + }, this ); }, - + /** * Find the Store's collection for a certain type of model. - * @param {Backbone.RelationalModel} 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 */ - getCollection: function( model ) { - if ( model instanceof Backbone.RelationalModel ) { - model = model.constructor; + getCollection: function( type, create ) { + if ( type instanceof Backbone.RelationalModel ) { + type = type.constructor; } - var rootModel = model; + var rootModel = type; while ( rootModel._superModel ) { rootModel = rootModel._superModel; } - var coll = _.detect( this._collections, function( c ) { - return c.model === rootModel; - }); + var coll = _.findWhere( this._collections, { model: rootModel } ); - if ( !coll ) { + if ( !coll && create !== false ) { coll = this._createCollection( rootModel ); } return coll; }, - + /** - * Find a type on the global object by name. Splits name on dots. + * Find a model type on one of the modelScopes by name. Names are split on dots. * @param {String} name * @return {Object} */ @@ -253,8 +317,8 @@ type = null; _.find( this._modelScopes, function( scope ) { - type = _.reduce( parts, function( memo, val ) { - return memo[ val ]; + type = _.reduce( parts || [], function( memo, val ) { + return memo ? memo[ val ] : undefined; }, scope ); if ( type && type !== scope ) { @@ -264,7 +328,7 @@ return type; }, - + _createCollection: function( type ) { var coll; @@ -311,7 +375,7 @@ }, /** - * + * Find a specific model of a certain `type` in the store * @param type * @param {String|Number|Object|Backbone.RelationalModel} item */ @@ -331,52 +395,82 @@ return null; }, - + /** - * Add a 'model' to it's appropriate collection. Retain the original contents of 'model.collection'. + * Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'. * @param {Backbone.RelationalModel} model */ register: function( model ) { var coll = this.getCollection( model ); if ( coll ) { - if ( coll.get( model ) ) { - throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" ); - } - var modelColl = model.collection; coll.add( model ); - model.bind( 'destroy', this.unregister, this ); + this.listenTo( model, 'destroy', this.unregister, this ); model.collection = modelColl; } }, - + /** - * Explicitly update a model's id in it's store collection + * Check if the given model may use the given `id` + * @param model + * @param [id] + */ + checkId: function( model, id ) { + var coll = this.getCollection( model ), + duplicate = coll && coll.get( id ); + + if ( duplicate && model !== duplicate ) { + if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { + console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model ); + } + + 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 */ update: function( model ) { var coll = this.getCollection( model ); + // This triggers updating the lookup indices kept in a collection coll._onModelEvent( 'change:' + model.idAttribute, model, coll ); + + // Trigger an event on model so related models (having the model's new id in their keyContents) can add it. + model.trigger( 'relational:change:id', model, coll ); }, - + /** * Remove a 'model' from the store. * @param {Backbone.RelationalModel} model */ unregister: function( model ) { - model.unbind( 'destroy', this.unregister ); + this.stopListening( model, 'destroy', this.unregister ); var coll = this.getCollection( model ); coll && coll.remove( model ); + }, + + /** + * 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(); + this._collections = []; + this._subModels = []; + this._modelScopes = [ exports ]; } }); Backbone.Relational.store = new Backbone.Store(); - + /** * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:' events * are used to regulate addition and removal of models from relations. * - * @param {Backbone.RelationalModel} instance + * @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 @@ -385,41 +479,30 @@ * @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 */ - Backbone.Relation = function( instance, options ) { + Backbone.Relation = function( instance, options, opts ) { this.instance = instance; // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype options = _.isObject( options ) ? options : {}; this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation ); + this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options ); + this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type : Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type ); - this.model = options.model || this.instance.constructor; - this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options ); - + this.key = this.options.key; this.keySource = this.options.keySource || this.key; this.keyDestination = this.options.keyDestination || this.keySource || this.key; - // 'exports' should be the global object where 'relatedModel' can be found on if given as a string. + this.model = this.options.model || this.instance.constructor; this.relatedModel = this.options.relatedModel; if ( _.isString( this.relatedModel ) ) { this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel ); } if ( !this.checkPreconditions() ) { - return false; - } - - if ( instance ) { - this.keyContents = this.instance.get( this.keySource ); - - // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. - if ( this.key !== this.keySource ) { - this.instance.unset( this.keySource, { silent: true } ); - } - - // Add this Relation to instance._relations - this.instance._relations.push( this ); + return; } // Add the reverse relation on 'relatedModel' to the store's reverseRelations @@ -428,25 +511,39 @@ isAutoRelation: true, model: this.relatedModel, relatedModel: this.model, - reverseRelation: this.options // current relation is the 'reverseRelation' for it's own reverseRelation + reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation }, this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.) ) ); } - _.bindAll( this, '_modelRemovedFromCollection', '_relatedModelAdded', '_relatedModelRemoved' ); + if ( instance ) { + var contentKey = this.keySource; + if ( contentKey !== this.key && typeof this.instance.get( this.key ) === 'object' ) { + contentKey = this.key; + } + + this.setKeyContents( this.instance.get( contentKey ) ); + this.relatedCollection = Backbone.Relational.store.getCollection( this.relatedModel ); - if ( instance ) { - this.initialize(); + // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. + if ( this.keySource !== this.key ) { + this.instance.unset( this.keySource, { silent: true } ); + } - // When a model in the store is destroyed, check if it is 'this.instance'. - Backbone.Relational.store.getCollection( this.instance ) - .bind( 'relational:remove', this._modelRemovedFromCollection ); + // Add this Relation to instance._relations + this.instance._relations[ this.key ] = this; + + this.initialize( opts ); + + if ( this.options.autoFetch ) { + this.instance.fetchRelated( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} ); + } // When 'relatedModel' are created or destroyed, check if it affects this relation. - Backbone.Relational.store.getCollection( this.relatedModel ) - .bind( 'relational:add', this._relatedModelAdded ) - .bind( 'relational:remove', this._relatedModelRemoved ); + this.listenTo( this.instance, 'destroy', this.destroy ) + .listenTo( this.relatedCollection, 'relational:add relational:change:id', this.tryAddRelated ) + .listenTo( this.relatedCollection, 'relational:remove', this.removeRelated ) } }; // Fix inheritance :\ @@ -456,35 +553,19 @@ options: { createModels: true, includeInJSON: true, - isAutoRelation: false + isAutoRelation: false, + autoFetch: false, + parse: false }, - + instance: null, key: null, keyContents: null, relatedModel: null, + relatedCollection: null, reverseRelation: null, related: null, - - _relatedModelAdded: function( model, coll, options ) { - // Allow 'model' to set up it's relations, before calling 'tryAddRelated' - // (which can result in a call to 'addRelated' on a relation of 'model') - var dit = this; - model.queue( function() { - dit.tryAddRelated( model, options ); - }); - }, - - _relatedModelRemoved: function( model, coll, options ) { - this.removeRelated( model, options ); - }, - - _modelRemovedFromCollection: function( model ) { - if ( model === this.instance ) { - this.destroy(); - } - }, - + /** * Check several pre-conditions. * @return {Boolean} True if pre-conditions are satisfied, false if they're not. @@ -497,36 +578,33 @@ warn = Backbone.Relational.showWarnings && typeof console !== 'undefined'; if ( !m || !k || !rm ) { - warn && console.warn( 'Relation=%o; no model, key or relatedModel (%o, %o, %o)', this, 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 if ( !( m.prototype instanceof Backbone.RelationalModel ) ) { - warn && console.warn( 'Relation=%o; model does not inherit from Backbone.RelationalModel (%o)', this, i ); + 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 if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) { - warn && console.warn( 'Relation=%o; relatedModel does not inherit from Backbone.RelationalModel (%o)', this, rm ); + 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 if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) { - warn && console.warn( 'Relation=%o; relation is a HasMany, and the reverseRelation is HasMany as well.', this ); + 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. + if ( i && _.keys( i._relations ).length ) { + var existing = _.find( i._relations, function( rel ) { + return rel.key === k; + }, this ); - // Check if we're not attempting to create a duplicate relationship - if ( i && i._relations.length ) { - var exists = _.any( i._relations, function( rel ) { - var hasReverseRelation = this.reverseRelation.key && rel.reverseRelation.key; - return rel.relatedModel === rm && rel.key === k && - ( !hasReverseRelation || this.reverseRelation.key === rel.reverseRelation.key ); - }, this ); - - if ( exists ) { - warn && console.warn( 'Relation=%o between instance=%o.%s and relatedModel=%o.%s already exists', - this, i, k, rm, this.reverseRelation.key ); + 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; } } @@ -536,17 +614,16 @@ /** * Set the related model(s) for this relation - * @param {Backbone.Mode|Backbone.Collection} related - * @param {Object} [options] + * @param {Backbone.Model|Backbone.Collection} related */ - setRelated: function( related, options ) { + setRelated: function( related ) { this.related = related; this.instance.acquire(); - this.instance.set( this.key, related, _.defaults( options || {}, { silent: true } ) ); + this.instance.attributes[ this.key ] = related; this.instance.release(); }, - + /** * Determine if a relation (on a different RelationalModel) is the reverse * relation of the current one. @@ -554,13 +631,10 @@ * @return {Boolean} */ _isReverseRelation: function( relation ) { - if ( relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key && - this.key === relation.reverseRelation.key ) { - return true; - } - return false; + return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key && + this.key === relation.reverseRelation.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. @@ -571,97 +645,92 @@ 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 ] ); - _.each( models , function( related ) { - _.each( related.getRelations(), function( relation ) { - if ( this._isReverseRelation( relation ) ) { - reverseRelations.push( relation ); - } - }, this ); - }, this ); + _.each( models || [], function( related ) { + _.each( related.getRelations() || [], function( relation ) { + if ( this._isReverseRelation( relation ) ) { + reverseRelations.push( relation ); + } + }, this ); + }, this ); return reverseRelations; }, - - /** - * Rename options.silent to options.silentChange, so events propagate properly. - * (for example in HasMany, from 'addRelated'->'handleAddition') - * @param {Object} [options] - * @return {Object} - */ - sanitizeOptions: function( options ) { - options = options ? _.clone( options ) : {}; - if ( options.silent ) { - options.silentChange = true; - delete options.silent; - } - return options; - }, /** - * Rename options.silentChange to options.silent, so events are silenced as intended in Backbone's - * original functions. - * @param {Object} [options] - * @return {Object} + * When `this.instance` is destroyed, cleanup our relations. + * Get reverse relation, call removeRelated on each. */ - unsanitizeOptions: function( options ) { - options = options ? _.clone( options ) : {}; - if ( options.silentChange ) { - options.silent = true; - delete options.silentChange; + destroy: function() { + this.stopListening(); + + if ( this instanceof Backbone.HasOne ) { + this.setRelated( null ); } - return options; - }, - - // Cleanup. Get reverse relation, call removeRelated on each. - destroy: function() { - Backbone.Relational.store.getCollection( this.instance ) - .unbind( 'relational:remove', this._modelRemovedFromCollection ); - - Backbone.Relational.store.getCollection( this.relatedModel ) - .unbind( 'relational:add', this._relatedModelAdded ) - .unbind( 'relational:remove', this._relatedModelRemoved ); + else if ( this instanceof Backbone.HasMany ) { + this.setRelated( this._prepareCollection() ); + } _.each( this.getReverseRelations(), function( relation ) { - relation.removeRelated( this.instance ); - }, this ); + relation.removeRelated( this.instance ); + }, this ); } }); - + Backbone.HasOne = Backbone.Relation.extend({ options: { reverseRelation: { type: 'HasMany' } }, - - initialize: function() { - _.bindAll( this, 'onChange' ); - this.instance.bind( 'relational:change:' + this.key, this.onChange ); + initialize: function( opts ) { + this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange ); - var model = this.findRelated( { silent: true } ); - this.setRelated( model ); + var related = this.findRelated( opts ); + this.setRelated( related ); // Notify new 'related' object of the new relation. _.each( this.getReverseRelations(), function( relation ) { - relation.addRelated( this.instance ); - }, this ); + relation.addRelated( this.instance, opts ); + }, this ); }, - + + /** + * Find related Models. + * @param {Object} [options] + * @return {Backbone.Model} + */ findRelated: function( options ) { - var item = this.keyContents; - var model = null; - - if ( item instanceof this.relatedModel ) { - model = item; + var related = null; + + options = _.defaults( { parse: this.options.parse }, options ); + + if ( this.keyContents instanceof this.relatedModel ) { + related = this.keyContents; + } + else if ( this.keyContents || this.keyContents === 0 ) { // since 0 can be a valid `id` as well + var opts = _.defaults( { create: this.options.createModels }, options ); + related = this.relatedModel.findOrCreate( this.keyContents, opts ); + } + + // Nullify `keyId` if we have a related model; in case it was already part of the relation + if ( this.related ) { + this.keyId = null; } - else if ( item || item === 0 ) { // since 0 can be a valid `id` as well - model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } ); - } - - return model; + + return related; }, - + /** - * If the key is changed, notify old & new reverse relations and initialize the new relation + * Normalize and reduce `keyContents` to an `id`, for easier comparison + * @param {String|Number|Backbone.Model} keyContents + */ + setKeyContents: function( keyContents ) { + this.keyContents = keyContents; + this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents ); + }, + + /** + * Event handler for `change:`. + * If the key is changed, notify old & new reverse relations and initialize the new relation. */ onChange: function( model, attr, options ) { // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange) @@ -669,81 +738,70 @@ return; } this.acquire(); - options = this.sanitizeOptions( options ); + options = options ? _.clone( options ) : {}; - // 'options._related' is set by 'addRelated'/'removeRelated'. If it is set, the change + // '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. - var changed = _.isUndefined( options._related ); - var oldRelated = changed ? this.related : options._related; + var changed = _.isUndefined( options.__related ), + oldRelated = changed ? this.related : options.__related; - if ( changed ) { - this.keyContents = attr; - - // Set new 'related' - if ( attr instanceof this.relatedModel ) { - this.related = attr; - } - else if ( attr ) { - var related = this.findRelated( options ); - this.setRelated( related ); - } - else { - this.setRelated( null ); - } + if ( changed ) { + this.setKeyContents( attr ); + var related = this.findRelated( options ); + this.setRelated( related ); } // Notify old 'related' object of the terminated relation if ( oldRelated && this.related !== oldRelated ) { _.each( this.getReverseRelations( oldRelated ), function( relation ) { - relation.removeRelated( this.instance, options ); - }, this ); + relation.removeRelated( this.instance, null, options ); + }, 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. _.each( this.getReverseRelations(), function( relation ) { - relation.addRelated( this.instance, options ); - }, this); + relation.addRelated( this.instance, options ); + }, this ); - // Fire the 'update:' event if 'related' was updated - if ( !options.silentChange && this.related !== oldRelated ) { + // Fire the 'change:' event if 'related' was updated + if ( !options.silent && this.related !== oldRelated ) { var dit = this; + this.changed = true; Backbone.Relational.eventQueue.add( function() { - dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options ); + dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true ); + dit.changed = false; }); } this.release(); }, - + /** * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents' */ - tryAddRelated: function( model, options ) { - if ( this.related ) { - return; - } - options = this.sanitizeOptions( options ); - - var item = this.keyContents; - if ( item || item === 0 ) { // since 0 can be a valid `id` as well - var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); - if ( !_.isNull( id ) && model.id === id ) { - this.addRelated( model, options ); - } + tryAddRelated: function( model, coll, options ) { + if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well + this.addRelated( model, options ); + this.keyId = null; } }, - + addRelated: function( model, options ) { - if ( model !== this.related ) { - var oldRelated = this.related || null; - this.setRelated( model ); - this.onChange( this.instance, model, { _related: oldRelated } ); - } + // 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; + model.queue( function() { + if ( model !== dit.related ) { + var oldRelated = dit.related || null; + dit.setRelated( model ); + dit.onChange( dit.instance, model, _.defaults( { __related: oldRelated }, options ) ); + } + }); }, - - removeRelated: function( model, options ) { + + removeRelated: function( model, coll, options ) { if ( !this.related ) { return; } @@ -751,66 +809,53 @@ if ( model === this.related ) { var oldRelated = this.related || null; this.setRelated( null ); - this.onChange( this.instance, model, { _related: oldRelated } ); + this.onChange( this.instance, model, _.defaults( { __related: oldRelated }, options ) ); } } }); - + Backbone.HasMany = Backbone.Relation.extend({ collectionType: null, - + options: { reverseRelation: { type: 'HasOne' }, collectionType: Backbone.Collection, collectionKey: true, collectionOptions: {} }, - - initialize: function() { - _.bindAll( this, 'onChange', 'handleAddition', 'handleRemoval', 'handleReset' ); - this.instance.bind( 'relational:change:' + this.key, this.onChange ); + + initialize: function( opts ) { + this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange ); // Handle a custom 'collectionType' this.collectionType = this.options.collectionType; if ( _.isString( this.collectionType ) ) { this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType ); } - if ( !this.collectionType.prototype instanceof Backbone.Collection ){ - throw new Error( 'collectionType must inherit from Backbone.Collection' ); + if ( this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) { + throw new Error( '`collectionType` must inherit from Backbone.Collection' ); } - // Handle cases where a model/relation is created with a collection passed straight into 'attributes' - if ( this.keyContents instanceof Backbone.Collection ) { - this.setRelated( this._prepareCollection( this.keyContents ) ); - } - else { - this.setRelated( this._prepareCollection() ); - } - - this.findRelated( { silent: true } ); - }, - - _getCollectionOptions: function() { - return _.isFunction( this.options.collectionOptions ) ? - this.options.collectionOptions( this.instance ) : - this.options.collectionOptions; + var related = this.findRelated( opts ); + 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.related - .unbind( 'relational:add', this.handleAddition ) - .unbind( 'relational:remove', this.handleRemoval ) - .unbind( 'relational:reset', this.handleReset ) + this.stopListening( this.related ); } if ( !collection || !( collection instanceof Backbone.Collection ) ) { - collection = new this.collectionType( [], this._getCollectionOptions() ); + var options = _.isFunction( this.options.collectionOptions ) ? + this.options.collectionOptions( this.instance ) : this.options.collectionOptions; + + collection = new this.collectionType( null, options ); } collection.model = this.relatedModel; @@ -827,191 +872,191 @@ collection[ key ] = this.instance; } } - - collection - .bind( 'relational:add', this.handleAddition ) - .bind( 'relational:remove', this.handleRemoval ) - .bind( 'relational:reset', this.handleReset ); + + this.listenTo( collection, 'relational:add', this.handleAddition ) + .listenTo( collection, 'relational:remove', this.handleRemoval ) + .listenTo( collection, 'relational:reset', this.handleReset ); return collection; }, - + + /** + * Find related Models. + * @param {Object} [options] + * @return {Backbone.Collection} + */ findRelated: function( options ) { - if ( this.keyContents ) { - var models = []; + var related = null; + + options = _.defaults( { parse: this.options.parse }, options ); + + // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection + if ( this.keyContents instanceof 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 = []; - if ( this.keyContents instanceof Backbone.Collection ) { - models = this.keyContents.models; + _.each( this.keyContents, function( attributes ) { + if ( attributes instanceof this.relatedModel ) { + var model = attributes; + } + else { + // If `merge` is true, update models here, instead of during update. + model = this.relatedModel.findOrCreate( attributes, + _.extend( { merge: true }, options, { create: this.options.createModels } ) + ); + } + + model && toAdd.push( model ); + }, this ); + + if ( this.related instanceof Backbone.Collection ) { + related = this.related; } else { - // Handle cases the an API/user supplies just an Object/id instead of an Array - this.keyContents = _.isArray( this.keyContents ) ? this.keyContents : [ this.keyContents ]; - - // Try to find instances of the appropriate 'relatedModel' in the store - _.each( this.keyContents, function( item ) { - var model = null; - if ( item instanceof this.relatedModel ) { - model = item; - } - else if ( item || item === 0 ) { // since 0 can be a valid `id` as well - model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } ); - } - - if ( model && !this.related.getByCid( model ) && !this.related.get( model ) ) { - models.push( model ); - } - }, this ); + related = this._prepareCollection(); } - // Add all found 'models' in on go, so 'add' will only be called once (and thus 'sort', etc.) - if ( models.length ) { - options = this.unsanitizeOptions( options ); - this.related.add( models, options ); - } + // By now, both `merge` and `parse` will already have been executed for models if they were specified. + // Disable them to prevent additional calls. + related.set( toAdd, _.defaults( { merge: false, parse: false }, options ) ); + } + + // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged') + this.keyIds = _.difference( this.keyIds, _.pluck( related.models, 'id' ) ); + + 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.keyContents = keyContents instanceof Backbone.Collection ? keyContents : null; + this.keyIds = []; + + if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well + // Handle cases the an API/user supplies just an Object/id instead of an Array + this.keyContents = _.isArray( keyContents ) ? keyContents : [ keyContents ]; + + _.each( this.keyContents, function( item ) { + var itemId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); + if ( itemId || itemId === 0 ) { + this.keyIds.push( itemId ); + } + }, this ); } }, - + /** - * If the key is changed, notify old & new reverse relations and initialize the new relation + * Event handler for `change:`. + * If the contents of the key are changed, notify old & new reverse relations and initialize the new relation. */ onChange: function( model, attr, options ) { - options = this.sanitizeOptions( options ); - this.keyContents = attr; - - // Notify old 'related' object of the terminated relation - _.each( this.getReverseRelations(), function( relation ) { - relation.removeRelated( this.instance, options ); - }, this ); - - // Replace 'this.related' by 'attr' if it is a Backbone.Collection - if ( attr instanceof Backbone.Collection ) { - this._prepareCollection( attr ); - this.related = attr; - } - // Otherwise, 'attr' should be an array of related object ids. - // Re-use the current 'this.related' if it is a Backbone.Collection, and remove any current entries. - // Otherwise, create a new collection. - else { - var coll; + options = options ? _.clone( options ) : {}; + this.setKeyContents( attr ); + this.changed = false; - if ( this.related instanceof Backbone.Collection ) { - coll = this.related; - coll.remove( coll.models ); - } - else { - coll = this._prepareCollection(); - } + var related = this.findRelated( options ); + this.setRelated( related ); - this.setRelated( coll ); - this.findRelated( options ); - } - - // Notify new 'related' object of the new relation - _.each( this.getReverseRelations(), function( relation ) { - relation.addRelated( this.instance, options ); - }, this ); - - var dit = this; - Backbone.Relational.eventQueue.add( function() { - !options.silentChange && dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options ); - }); - }, - - tryAddRelated: function( model, options ) { - options = this.sanitizeOptions( options ); - if ( !this.related.getByCid( model ) && !this.related.get( model ) ) { - // Check if this new model was specified in 'this.keyContents' - var item = _.any( this.keyContents, function( item ) { - var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); - return !_.isNull( id ) && id === model.id; - }, this ); - - if ( item ) { - this.related.add( model, options ); - } + if ( !options.silent ) { + var dit = this; + Backbone.Relational.eventQueue.add( function() { + // The `changed` flag can be set in `handleAddition` or `handleRemoval` + if ( dit.changed ) { + dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true ); + dit.changed = false; + } + }); } }, - + /** * 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). - */ + */ handleAddition: function( model, coll, options ) { //console.debug('handleAddition called; args=%o', arguments); - // Make sure the model is in fact a valid model before continuing. - // (it can be invalid as a result of failing validation in Backbone.Collection._prepareModel) - if ( !( model instanceof Backbone.Model ) ) { - return; - } - - options = this.sanitizeOptions( options ); + options = options ? _.clone( options ) : {}; + this.changed = true; _.each( this.getReverseRelations( model ), function( relation ) { - relation.addRelated( this.instance, options ); - }, this ); + relation.addRelated( this.instance, options ); + }, this ); - // Only trigger 'add' once the newly added model is initialized (so, has it's relations set up) + // Only trigger 'add' once the newly added model is initialized (so, has its relations set up) var dit = this; - Backbone.Relational.eventQueue.add( function() { - !options.silentChange && dit.instance.trigger( 'add:' + dit.key, model, dit.related, options ); + !options.silent && Backbone.Relational.eventQueue.add( function() { + dit.instance.trigger( 'add:' + dit.key, model, dit.related, options ); }); }, - + /** * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations. * (should be 'HasOne', which should be nullified) */ handleRemoval: function( model, coll, options ) { //console.debug('handleRemoval called; args=%o', arguments); - if ( !( model instanceof Backbone.Model ) ) { - return; - } - - options = this.sanitizeOptions( options ); + options = options ? _.clone( options ) : {}; + this.changed = true; _.each( this.getReverseRelations( model ), function( relation ) { - relation.removeRelated( this.instance, options ); - }, this ); + relation.removeRelated( this.instance, null, options ); + }, this ); var dit = this; - Backbone.Relational.eventQueue.add( function() { - !options.silentChange && dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options ); + !options.silent && Backbone.Relational.eventQueue.add( function() { + dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options ); }); }, handleReset: function( coll, options ) { - options = this.sanitizeOptions( options ); - var dit = this; - Backbone.Relational.eventQueue.add( function() { - !options.silentChange && dit.instance.trigger( 'reset:' + dit.key, dit.related, options ); + options = options ? _.clone( options ) : {}; + !options.silent && Backbone.Relational.eventQueue.add( function() { + dit.instance.trigger( 'reset:' + dit.key, dit.related, options ); }); }, - + + tryAddRelated: function( model, coll, options ) { + var item = _.contains( this.keyIds, model.id ); + + if ( item ) { + this.addRelated( model, options ); + this.keyIds = _.without( this.keyIds, model.id ); + } + }, + addRelated: function( model, options ) { + // 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; - options = this.unsanitizeOptions( options ); - model.queue( function() { // Queued to avoid errors for adding 'model' to the 'this.related' set twice - if ( dit.related && !dit.related.getByCid( model ) && !dit.related.get( model ) ) { - dit.related.add( model, options ); + model.queue( function() { + if ( dit.related && !dit.related.get( model ) ) { + dit.related.add( model, _.defaults( { parse: false }, options ) ); } }); }, - - removeRelated: function( model, options ) { - options = this.unsanitizeOptions( options ); - if ( this.related.getByCid( model ) || this.related.get( model ) ) { + + removeRelated: function( model, coll, options ) { + if ( this.related.get( model ) ) { this.related.remove( model, options ); } } }); - + /** * A type of Backbone.Model that also maintains relations to other models and collections. * New events when compared to the original: * - 'add:' (model, related collection, options) * - 'remove:' (model, related collection, options) - * - 'update:' (model, related model or collection, options) + * - 'change:' (model, related model or collection, options) */ Backbone.RelationalModel = Backbone.Model.extend({ relations: null, // Relation descriptions on the prototype @@ -1019,82 +1064,118 @@ _isInitialized: false, _deferProcessing: false, _queue: null, - + subModelTypeAttribute: 'type', subModelTypes: null, - + constructor: function( attributes, options ) { // Nasty hack, for cases like 'model.get( ).add( item )'. - // Defer 'processQueue', so that when 'Relation.createModels' is used we: - // a) Survive 'Backbone.Collection.add'; this takes care we won't error on "can't add model to a set twice" - // (by creating a model from properties, having the model add itself to the collection via one of - // it's relations, then trying to add it to the collection). - // b) Trigger 'HasMany' collection events only after the model is really fully set up. - // Example that triggers both a and b: "p.get('jobs').add( { company: c, person: p } )". - var dit = this; + // 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 } )". if ( options && options.collection ) { + var dit = this, + collection = this.collection = options.collection; + + // 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 ) { if ( model === dit ) { dit._deferProcessing = false; dit.processQueue(); - options.collection.unbind( 'relational:add', processQueue ); + collection.off( 'relational:add', processQueue ); } }; - options.collection.bind( 'relational:add', processQueue ); - - // So we do process the queue eventually, regardless of whether this model really gets added to 'options.collection'. + collection.on( 'relational:add', 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.processOrphanRelations(); this._queue = new Backbone.BlockingQueue(); this._queue.block(); Backbone.Relational.eventQueue.block(); - - Backbone.Model.apply( this, arguments ); - - // Try to run the global queue holding external events - Backbone.Relational.eventQueue.unblock(); + + try { + Backbone.Model.apply( this, arguments ); + } + finally { + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); + } }, - + /** * Override 'trigger' to queue 'change' and 'change:*' events */ trigger: function( eventName ) { - if ( eventName.length > 5 && 'change' === eventName.substr( 0, 6 ) ) { - var dit = this, args = arguments; + if ( eventName.length > 5 && eventName.indexOf( 'change' ) === 0 ) { + var dit = this, + args = arguments; + Backbone.Relational.eventQueue.add( function() { - Backbone.Model.prototype.trigger.apply( dit, args ); - }); + if ( !dit._isInitialized ) { + return; + } + + // Determine if the `change` event is still valid, now that all relations are populated + var changed = true; + if ( eventName === 'change' ) { + changed = dit.hasChanged(); + } + else { + var attr = eventName.slice( 7 ), + rel = dit.getRelation( attr ); + + 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 set a fourth attribute to `true`. If this attribute is present, + // continue triggering this event; otherwise, it's from `Model.set` and should be stopped. + changed = ( args[ 4 ] === true ); + + // 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 ) { + dit.changed[ attr ] = args[ 2 ]; + } + // 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 ( !rel.changed ) { + delete dit.changed[ attr ]; + } + } + } + + changed && Backbone.Model.prototype.trigger.apply( dit, args ); + }); } else { Backbone.Model.prototype.trigger.apply( this, arguments ); } - + 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() { + 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 = []; - - _.each( this.relations, function( rel ) { - var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type ); - if ( type && type.prototype instanceof Backbone.Relation ) { - new type( this, rel ); // Also pushes the new Relation into _relations - } - else { - Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid type!', rel ); - } - }, this ); - + this._relations = {}; + + _.each( this.relations || [], function( rel ) { + Backbone.Relational.store.initializeRelation( this, rel, options ); + }, this ); + this._isInitialized = true; this.release(); this.processQueue(); @@ -1115,14 +1196,14 @@ }, this ); } }, - + /** * Either add to the queue (if we're not initialized yet), or execute right away. */ queue: function( func ) { this._queue.add( func ); }, - + /** * Process _queue */ @@ -1131,68 +1212,71 @@ this._queue.unblock(); } }, - + /** * Get a specific relation. * @param key {string} The relation key to look for. * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'key', or null. */ getRelation: function( key ) { - return _.detect( this._relations, function( rel ) { - if ( rel.key === key ) { - return true; - } - }, this ); + return this._relations[ key ]; }, - + /** * Get all of the created relations. * @return {Backbone.Relation[]} */ getRelations: function() { - return this._relations; + return _.values( this._relations ); }, - + /** * Retrieve related objects. * @param key {string} The relation key to fetch models for. * @param [options] {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'. - * @param [update=false] {boolean} Whether to force a fetch from the server (updating existing models). + * @param [refresh=false] {boolean} Fetch existing models from the server as well (in order to update them). * @return {jQuery.when[]} An array of request objects */ - fetchRelated: function( key, options, update ) { - options || ( options = {} ); + fetchRelated: function( key, options, refresh ) { + // Set default `options` for fetch + options = _.extend( { update: true, remove: false }, options ); + var setUrl, requests = [], rel = this.getRelation( key ), - keyContents = rel && rel.keyContents, - toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) { - var id = Backbone.Relational.store.resolveIdForItem( rel.relatedModel, item ); - return !_.isNull( id ) && ( update || !Backbone.Relational.store.find( rel.relatedModel, id ) ); - }, this ); - - if ( toFetch && toFetch.length ) { - // Create a model for each entry in 'keyContents' that is to be fetched - var models = _.map( toFetch, function( item ) { - var model; + idsToFetch = rel && ( rel.keyIds || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) ); + + // On `refresh`, add the ids for current models in the relation to `idsToFetch` + if ( refresh ) { + var models = rel.related instanceof Backbone.Collection ? rel.related.models : [ rel.related ]; + _.each( models, function( model ) { + if ( model.id || model.id === 0 ) { + idsToFetch.push( model.id ); + } + }); + } - if ( _.isObject( item ) ) { - model = rel.relatedModel.build( item ); - } - else { - var attrs = {}; - attrs[ rel.relatedModel.prototype.idAttribute ] = item; - model = rel.relatedModel.build( attrs ); - } + if ( idsToFetch && idsToFetch.length ) { + // Find (or create) a model for each one that is to be fetched + var created = [], + models = _.map( idsToFetch, function( id ) { + var model = Backbone.Relational.store.find( rel.relatedModel, id ); + + if ( !model ) { + var attrs = {}; + attrs[ rel.relatedModel.prototype.idAttribute ] = id; + model = rel.relatedModel.findOrCreate( attrs, options ); + created.push( model ); + } - return model; - }, this ); + return model; + }, this ); // Try if the 'collection' can provide a url to fetch a set of models in one request. if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) { setUrl = rel.related.url( models ); } - + // An assumption is 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'). @@ -1201,15 +1285,14 @@ { error: function() { var args = arguments; - _.each( models, function( model ) { - model.trigger( 'destroy', model, model.collection, options ); - options.error && options.error.apply( model, args ); - }); + _.each( created, function( model ) { + model.trigger( 'destroy', model, model.collection, options ); + options.error && options.error.apply( model, args ); + }); }, url: setUrl }, - options, - { add: true } + options ); requests = [ rel.related.fetch( opts ) ]; @@ -1219,8 +1302,10 @@ var opts = _.defaults( { error: function() { - model.trigger( 'destroy', model, model.collection, options ); - options.error && options.error.apply( model, arguments ); + if ( _.contains( created, model ) ) { + model.trigger( 'destroy', model, model.collection, options ); + options.error && options.error.apply( model, arguments ); + } } }, options @@ -1232,10 +1317,35 @@ return requests; }, - + + get: function( attr ) { + var originalResult = Backbone.Model.prototype.get.call( this, attr ); + + // Use `originalResult` get if dotNotation not enabled or not required because no dot is in `attr` + if ( !this.dotNotation || attr.indexOf( '.' ) === -1 ) { + return originalResult; + } + + // Go through all splits and return the final result + var splits = attr.split( '.' ); + var result = _.reduce(splits, function( model, split ) { + if ( !( model instanceof Backbone.Model ) ) { + throw new Error( 'Attribute must be an instanceof Backbone.Model. Is: ' + model + ', currentSplit: ' + split ); + } + + return Backbone.Model.prototype.get.call( model, split ); + }, this ); + + if ( originalResult !== undefined && result !== undefined ) { + throw new Error( "Ambiguous result for '" + attr + "'. direct result: " + originalResult + ", dotNotation: " + result ); + } + + return originalResult || result; + }, + set: function( key, value, options ) { Backbone.Relational.eventQueue.block(); - + // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object var attributes; if ( _.isObject( key ) || key == null ) { @@ -1246,66 +1356,62 @@ attributes = {}; attributes[ key ] = value; } - - var result = Backbone.Model.prototype.set.apply( this, arguments ); - - // Ideal place to set up relations :) - if ( !this._isInitialized && !this.isLocked() ) { - this.constructor.initializeModelHierarchy(); + + try { + var id = this.id, + newId = attributes && this.idAttribute in attributes && attributes[ this.idAttribute ]; + + // Check if we're not setting a duplicate id before actually calling `set`. + Backbone.Relational.store.checkId( this, newId ); + + var result = Backbone.Model.prototype.set.apply( this, arguments ); - Backbone.Relational.store.register( this ); + // 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(); + Backbone.Relational.store.register( this ); + this.initializeRelations( options ); + } + // The store should know about an `id` update asap + else if ( newId && newId !== id ) { + Backbone.Relational.store.update( this ); + } - this.initializeRelations(); + if ( attributes ) { + this.updateRelations( options ); + } } - // Update the 'idAttribute' in Backbone.store if; we don't want it to miss an 'id' update due to {silent:true} - else if ( attributes && this.idAttribute in attributes ) { - Backbone.Relational.store.update( this ); + finally { + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); } - if ( attributes ) { - this.updateRelations( options ); - } - - // Try to run the global queue holding external events - Backbone.Relational.eventQueue.unblock(); - return result; }, - + unset: function( attribute, options ) { Backbone.Relational.eventQueue.block(); - + var result = Backbone.Model.prototype.unset.apply( this, arguments ); this.updateRelations( options ); - + // Try to run the global queue holding external events Backbone.Relational.eventQueue.unblock(); - + return result; }, - + clear: function( options ) { Backbone.Relational.eventQueue.block(); var result = Backbone.Model.prototype.clear.apply( this, arguments ); this.updateRelations( options ); - + // Try to run the global queue holding external events Backbone.Relational.eventQueue.unblock(); - + return result; }, - - /** - * Override 'change', so the change will only execute after 'set' has finised (relations are updated), - * and 'previousAttributes' will be available when the event is fired. - */ - change: function( options ) { - var dit = this, args = arguments; - Backbone.Relational.eventQueue.add( function() { - Backbone.Model.prototype.change.apply( dit, args ); - }); - }, clone: function() { var attributes = _.clone( this.attributes ); @@ -1314,87 +1420,97 @@ } _.each( this.getRelations(), function( rel ) { - delete attributes[ rel.key ]; - }); + delete attributes[ rel.key ]; + }); return new this.constructor( attributes ); }, - + /** * Convert relations to JSON, omits them when required */ - toJSON: function() { + toJSON: function( options ) { // If this Model has already been fully serialized in this branch once, return to avoid loops if ( this.isLocked() ) { return this.id; } - + this.acquire(); - var json = Backbone.Model.prototype.toJSON.call( this ); - + var json = Backbone.Model.prototype.toJSON.call( this, options ); + if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) { json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue; } - + _.each( this._relations, function( rel ) { - var value = json[ rel.key ]; + var related = json[ rel.key ], + includeInJSON = rel.options.includeInJSON, + value = null; - if ( rel.options.includeInJSON === true) { - if ( value && _.isFunction( value.toJSON ) ) { - json[ rel.keyDestination ] = value.toJSON(); - } - else { - json[ rel.keyDestination ] = null; + if ( includeInJSON === true ) { + if ( related && _.isFunction( related.toJSON ) ) { + value = related.toJSON( options ); + } + } + else if ( _.isString( includeInJSON ) ) { + if ( related instanceof Backbone.Collection ) { + value = related.pluck( includeInJSON ); + } + else if ( related instanceof Backbone.Model ) { + value = related.get( includeInJSON ); + } + + // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute` + if ( includeInJSON === rel.relatedModel.prototype.idAttribute ) { + if ( rel instanceof Backbone.HasMany ) { + value = value.concat( rel.keyIds ); } - } - else if ( _.isString( rel.options.includeInJSON ) ) { - if ( value instanceof Backbone.Collection ) { - json[ rel.keyDestination ] = value.pluck( rel.options.includeInJSON ); - } - else if ( value instanceof Backbone.Model ) { - json[ rel.keyDestination ] = value.get( rel.options.includeInJSON ); - } - else { - json[ rel.keyDestination ] = null; + else if ( rel instanceof Backbone.HasOne ) { + value = value || rel.keyId; } } - else if ( _.isArray( rel.options.includeInJSON ) ) { - if ( value instanceof Backbone.Collection ) { - var valueSub = []; - value.each( function( model ) { - var curJson = {}; - _.each( rel.options.includeInJSON, function( key ) { - curJson[ key ] = model.get( key ); - }); - valueSub.push( curJson ); + } + else if ( _.isArray( includeInJSON ) ) { + if ( related instanceof Backbone.Collection ) { + value = []; + related.each( function( model ) { + var curJson = {}; + _.each( includeInJSON, function( key ) { + curJson[ key ] = model.get( key ); }); - json[ rel.keyDestination ] = valueSub; - } - else if ( value instanceof Backbone.Model ) { - var valueSub = {}; - _.each( rel.options.includeInJSON, function( key ) { - valueSub[ key ] = value.get( key ); - }); - json[ rel.keyDestination ] = valueSub; - } - else { - json[ rel.keyDestination ] = null; - } + value.push( curJson ); + }); + } + else if ( related instanceof Backbone.Model ) { + value = {}; + _.each( includeInJSON, function( key ) { + value[ key ] = related.get( key ); + }); } - else { - delete json[ rel.key ]; - } + } + else { + delete json[ rel.key ]; + } - if ( rel.keyDestination !== rel.key ) { - delete json[ rel.key ]; - } - }); + if ( includeInJSON ) { + json[ rel.keyDestination ] = value; + } + + if ( rel.keyDestination !== rel.key ) { + delete json[ rel.key ]; + } + }); 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. @@ -1413,30 +1529,35 @@ } // Initialize all reverseRelations that belong to this new model. - _.each( this.prototype.relations, function( rel ) { - if ( !rel.model ) { - rel.model = this; + _.each( this.prototype.relations || [], function( rel ) { + if ( !rel.model ) { + rel.model = this; + } + + if ( rel.reverseRelation && rel.model === this ) { + var preInitialize = true; + if ( _.isString( rel.relatedModel ) ) { + /** + * 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. + */ + var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); + preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel ); } - if ( rel.reverseRelation && rel.model === this ) { - var preInitialize = true; - if ( _.isString( rel.relatedModel ) ) { - /** - * The related model might not be defined for two reasons - * 1. it never gets defined, e.g. a typo - * 2. it is related to itself - * In neither of these cases do we need to pre-initialize reverse relations. - */ - var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); - preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel ); - } - - var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type ); - if ( preInitialize && type && type.prototype instanceof Backbone.Relation ) { - new type( null, rel ); - } + if ( preInitialize ) { + Backbone.Relational.store.initializeRelation( null, rel ); } - }, this ); + else if ( _.isString( rel.relatedModel ) ) { + Backbone.Relational.store.addOrphanRelation( rel ); + } + } + }, this ); return this; }, @@ -1466,6 +1587,9 @@ return new model( attributes, options ); }, + /** + * + */ initializeModelHierarchy: function() { // If we're here for the first time, try to determine if this modelType has a 'superModel'. if ( _.isUndefined( this._superModel ) || _.isNull( this._superModel ) ) { @@ -1475,17 +1599,15 @@ // inherited automatically (due to a redefinition of 'relations'). // 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. - if ( this._superModel ) { - // - if ( this._superModel.prototype.relations ) { - var supermodelRelationsExist = _.any( this.prototype.relations, function( rel ) { - return rel.model && rel.model !== this; + if ( this._superModel && this._superModel.prototype.relations ) { + // Find relations that exist on the `_superModel`, but not yet on this model. + var inheritedRelations = _.select( this._superModel.prototype.relations || [], function( superRel ) { + return !_.any( this.prototype.relations || [], function( rel ) { + return superRel.relatedModel === rel.relatedModel && superRel.key === rel.key; }, this ); + }, this ); - if ( !supermodelRelationsExist ) { - this.prototype.relations = this._superModel.prototype.relations.concat( this.prototype.relations ); - } - } + this.prototype.relations = inheritedRelations.concat( this.prototype.relations ); } else { this._superModel = false; @@ -1494,7 +1616,7 @@ // If we came here through 'build' for a model that has 'subModelTypes', and not all of them have been resolved yet, try to resolve each. if ( this.prototype.subModelTypes && _.keys( this.prototype.subModelTypes ).length !== _.keys( this._subModels ).length ) { - _.each( this.prototype.subModelTypes, function( subModelTypeName ) { + _.each( this.prototype.subModelTypes || [], function( subModelTypeName ) { var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName ); subModelType && subModelType.initializeModelHierarchy(); }); @@ -1504,24 +1626,33 @@ /** * Find an instance of `this` type in 'Backbone.Relational.store'. * - If `attributes` is a string or a number, `findOrCreate` will just query the `store` and return a model if found. - * - If `attributes` is an object, the model will be updated with `attributes` if found. + * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.update` is `false`. * Otherwise, a new model is created with `attributes` (unless `options.create` is explicitly set to `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} */ findOrCreate: function( attributes, options ) { + options || ( options = {} ); + var parsedAttributes = ( _.isObject( attributes ) && options.parse && this.prototype.parse ) ? + this.prototype.parse( attributes ) : attributes; + // Try to find an instance of 'this' model type in the store - var model = Backbone.Relational.store.find( this, attributes ); + var model = Backbone.Relational.store.find( this, parsedAttributes ); - // If we found an instance, update it with the data in 'item'; if not, create an instance - // (unless 'options.create' is false). + // 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 ) ) { - if ( model ) { - model.set( model.parse ? model.parse( attributes ) : attributes, options ); + if ( model && options.merge !== false ) { + // Make sure `options.collection` doesn't cascade to nested models + delete options.collection; + + model.set( parsedAttributes, options ); } - else if ( !options || ( options && options.create !== false ) ) { + else if ( !model && options.create !== false ) { model = this.build( attributes, options ); } } @@ -1530,18 +1661,27 @@ } }); _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore ); - + /** * 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. */ Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel; - Backbone.Collection.prototype._prepareModel = function ( model, options ) { - options || (options = {}); - if ( !( model instanceof Backbone.Model ) ) { - var attrs = model; + Backbone.Collection.prototype._prepareModel = function ( attrs, options ) { + var model; + + if ( attrs instanceof Backbone.Model ) { + if ( !attrs.collection ) { + attrs.collection = this; + } + model = attrs; + } + else { + options || ( options = {} ); options.collection = this; - + if ( typeof this.model.findOrCreate !== 'undefined' ) { model = this.model.findOrCreate( attrs, options ); } @@ -1549,78 +1689,100 @@ model = new this.model( attrs, options ); } - if ( !model._validate( model.attributes, options ) ) { + if ( model && model.isNew() && !model._validate( attrs, options ) ) { + this.trigger( 'invalid', this, attrs, options ); model = false; } } - else if ( !model.collection ) { - model.collection = this; - } return model; - } - + }; + + /** - * Override Backbone.Collection.add, so objects fetched from the server multiple times will - * update the existing Model. Also, trigger 'relational:add'. + * Override Backbone.Collection.set, so we'll create objects from attributes where required, + * and update the existing models. Also, trigger 'relational:add'. */ - var add = Backbone.Collection.prototype.__add = Backbone.Collection.prototype.add; - Backbone.Collection.prototype.add = function( models, options ) { - options || (options = {}); - if ( !_.isArray( models ) ) { - models = [ models ]; + var set = Backbone.Collection.prototype.__set = Backbone.Collection.prototype.set; + Backbone.Collection.prototype.set = function( models, options ) { + // Short-circuit if this Collection doesn't hold RelationalModels + if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { + return set.apply( this, arguments ); } - var modelsToAdd = []; + if ( options && options.parse ) { + models = this.parse( models, options ); + } + + if ( !_.isArray( models ) ) { + models = models ? [ models ] : []; + } + + var newModels = [], + toAdd = []; //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options ); _.each( models, function( model ) { if ( !( model instanceof Backbone.Model ) ) { - // `_prepareModel` attempts to find `model` in Backbone.store through `findOrCreate`, - // and sets the new properties on it if is found. Otherwise, a new model is instantiated. model = Backbone.Collection.prototype._prepareModel.call( this, model, options ); } - if ( model instanceof Backbone.Model && !this.get( model ) && !this.getByCid( model ) ) { - modelsToAdd.push( model ); + if ( model ) { + toAdd.push( model ); + + if ( !( this.get( model ) || this.get( model.cid ) ) ) { + newModels.push( 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`. + else if ( model.id != null ) { + this._byId[ model.id ] = model; + } } }, this ); - // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc). - if ( modelsToAdd.length ) { - add.call( this, modelsToAdd, options ); + // If `parse` was specified, the collection and contained models have been parsed now. + set.call( this, toAdd, _.defaults( { parse: false }, options ) ); - _.each( modelsToAdd, function( model ) { + _.each( newModels, function( model ) { + // Fire a `relational:add` event for any model in `newModels` that has actually been added to the collection. + if ( this.get( model ) || this.get( model.cid ) ) { this.trigger( 'relational:add', model, this, options ); - }, this ); - } + } + }, this ); return this; }; - + /** * Override 'Backbone.Collection.remove' to trigger 'relational:remove'. */ var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove; Backbone.Collection.prototype.remove = function( models, options ) { - options || (options = {}); - if ( !_.isArray( models ) ) { - models = [ models ]; + // Short-circuit if this Collection doesn't hold RelationalModels + if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { + return remove.apply( this, arguments ); } - else { - models = models.slice( 0 ); - } + + models = _.isArray( models ) ? models.slice() : [ models ]; + options || ( options = {} ); + + var toRemove = []; //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options ); _.each( models, function( model ) { - model = this.getByCid( model ) || this.get( model ); + model = this.get( model ) || this.get( model.cid ); + model && toRemove.push( model ); + }, this ); - if ( model instanceof Backbone.Model ) { - remove.call( this, model, options ); - this.trigger('relational:remove', model, this, options); - } + if ( toRemove.length ) { + remove.call( this, toRemove, options ); + + _.each( toRemove, function( model ) { + this.trigger('relational:remove', model, this, options); }, this ); + } return this; }; @@ -1630,8 +1792,12 @@ */ var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset; Backbone.Collection.prototype.reset = function( models, options ) { + options = _.extend( { merge: true }, options ); reset.call( this, models, options ); - this.trigger( 'relational:reset', this, options ); + + if ( this.model.prototype instanceof Backbone.RelationalModel ) { + this.trigger( 'relational:reset', this, options ); + } return this; }; @@ -1642,32 +1808,39 @@ var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort; Backbone.Collection.prototype.sort = function( options ) { sort.call( this, options ); - this.trigger( 'relational:reset', this, options ); + + if ( this.model.prototype instanceof Backbone.RelationalModel ) { + this.trigger( 'relational:reset', this, options ); + } return this; }; - + /** * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations * are ready. */ var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger; Backbone.Collection.prototype.trigger = function( eventName ) { + // Short-circuit if this Collection doesn't hold RelationalModels + if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { + return trigger.apply( this, arguments ); + } + if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) { - var dit = this, args = arguments; + var dit = this, + args = arguments; - if (eventName === 'add') { - args = _.toArray(args); - // the fourth argument in case of a regular add is the option object. + if ( _.isObject( args[ 3 ] ) ) { + args = _.toArray( args ); + // 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 - if (_.isObject(args[3])) { - args[3] = _.clone(args[3]); - } + args[ 3 ] = _.clone( args[ 3 ] ); } Backbone.Relational.eventQueue.add( function() { - trigger.apply( dit, args ); - }); + trigger.apply( dit, args ); + }); } else { trigger.apply( this, arguments ); diff -r c472984db275 -r 1615c7e4ef9d src/js/libs/backbone.js --- a/src/js/libs/backbone.js Wed Apr 03 15:44:17 2013 +0200 +++ b/src/js/libs/backbone.js Tue Apr 23 15:23:20 2013 +0200 @@ -1,1431 +1,4 @@ -// Backbone.js 0.9.2 - -// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. -// Backbone may be freely distributed under the MIT license. -// For all details and documentation: -// http://backbonejs.org - -(function(){ - - // Initial Setup - // ------------- - - // Save a reference to the global object (`window` in the browser, `global` - // on the server). - var root = this; - - // Save the previous value of the `Backbone` variable, so that it can be - // restored later on, if `noConflict` is used. - var previousBackbone = root.Backbone; - - // Create a local reference to slice/splice. - var slice = Array.prototype.slice; - var splice = Array.prototype.splice; - - // The top-level namespace. All public Backbone classes and modules will - // be attached to this. Exported for both CommonJS and the browser. - var Backbone; - if (typeof exports !== 'undefined') { - Backbone = exports; - } else { - Backbone = root.Backbone = {}; - } - - // Current version of the library. Keep in sync with `package.json`. - Backbone.VERSION = '0.9.2'; - - // Require Underscore, if we're on the server, and it's not already present. - var _ = root._; - if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); - - // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. - var $ = root.jQuery || root.Zepto || root.ender; - - // Set the JavaScript library that will be used for DOM manipulation and - // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery, - // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an - // alternate JavaScript library (or a mock library for testing your views - // outside of a browser). - Backbone.setDomLibrary = function(lib) { - $ = lib; - }; - - // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable - // to its previous owner. Returns a reference to this Backbone object. - Backbone.noConflict = function() { - root.Backbone = previousBackbone; - return this; - }; - - // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option - // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and - // set a `X-Http-Method-Override` header. - Backbone.emulateHTTP = false; - - // Turn on `emulateJSON` to support legacy servers that can't deal with direct - // `application/json` requests ... will encode the body as - // `application/x-www-form-urlencoded` instead and will send the model in a - // form param named `model`. - Backbone.emulateJSON = false; - - // Backbone.Events - // ----------------- - - // Regular expression used to split event strings - var eventSplitter = /\s+/; - - // A module that can be mixed in to *any object* in order to provide it with - // custom events. You may bind with `on` or remove with `off` callback functions - // to an event; trigger`-ing an event fires all callbacks in succession. - // - // var object = {}; - // _.extend(object, Backbone.Events); - // object.on('expand', function(){ alert('expanded'); }); - // object.trigger('expand'); - // - var Events = Backbone.Events = { - - // Bind one or more space separated events, `events`, to a `callback` - // function. Passing `"all"` will bind the callback to all events fired. - on: function(events, callback, context) { - - var calls, event, node, tail, list; - if (!callback) return this; - events = events.split(eventSplitter); - calls = this._callbacks || (this._callbacks = {}); - - // Create an immutable callback list, allowing traversal during - // modification. The tail is an empty object that will always be used - // as the next node. - while (event = events.shift()) { - list = calls[event]; - node = list ? list.tail : {}; - node.next = tail = {}; - node.context = context; - node.callback = callback; - calls[event] = {tail: tail, next: list ? list.next : node}; - } - - return this; - }, - - // Remove one or many callbacks. If `context` is null, removes all callbacks - // with that function. If `callback` is null, removes all callbacks for the - // event. If `events` is null, removes all bound callbacks for all events. - off: function(events, callback, context) { - var event, calls, node, tail, cb, ctx; - - // No events, or removing *all* events. - if (!(calls = this._callbacks)) return; - if (!(events || callback || context)) { - delete this._callbacks; - return this; - } - - // Loop through the listed events and contexts, splicing them out of the - // linked list of callbacks if appropriate. - events = events ? events.split(eventSplitter) : _.keys(calls); - while (event = events.shift()) { - node = calls[event]; - delete calls[event]; - if (!node || !(callback || context)) continue; - // Create a new list, omitting the indicated callbacks. - tail = node.tail; - while ((node = node.next) !== tail) { - cb = node.callback; - ctx = node.context; - if ((callback && cb !== callback) || (context && ctx !== context)) { - this.on(event, cb, ctx); - } - } - } - - return this; - }, - - // Trigger one or many events, firing all bound callbacks. Callbacks are - // passed the same arguments as `trigger` is, apart from the event name - // (unless you're listening on `"all"`, which will cause your callback to - // receive the true name of the event as the first argument). - trigger: function(events) { - var event, node, calls, tail, args, all, rest; - if (!(calls = this._callbacks)) return this; - all = calls.all; - events = events.split(eventSplitter); - rest = slice.call(arguments, 1); - - // For each event, walk through the linked list of callbacks twice, - // first to trigger the event, then to trigger any `"all"` callbacks. - while (event = events.shift()) { - if (node = calls[event]) { - tail = node.tail; - while ((node = node.next) !== tail) { - node.callback.apply(node.context || this, rest); - } - } - if (node = all) { - tail = node.tail; - args = [event].concat(rest); - while ((node = node.next) !== tail) { - node.callback.apply(node.context || this, args); - } - } - } - - return this; - } - - }; - - // Aliases for backwards compatibility. - Events.bind = Events.on; - Events.unbind = Events.off; - - // Backbone.Model - // -------------- - - // Create a new model, with defined attributes. A client id (`cid`) - // is automatically generated and assigned for you. - var Model = Backbone.Model = function(attributes, options) { - var defaults; - attributes || (attributes = {}); - if (options && options.parse) attributes = this.parse(attributes); - if (defaults = getValue(this, 'defaults')) { - attributes = _.extend({}, defaults, attributes); - } - if (options && options.collection) this.collection = options.collection; - this.attributes = {}; - this._escapedAttributes = {}; - this.cid = _.uniqueId('c'); - this.changed = {}; - this._silent = {}; - this._pending = {}; - this.set(attributes, {silent: true}); - // Reset change tracking. - this.changed = {}; - this._silent = {}; - this._pending = {}; - this._previousAttributes = _.clone(this.attributes); - this.initialize.apply(this, arguments); - }; - - // Attach all inheritable methods to the Model prototype. - _.extend(Model.prototype, Events, { - - // A hash of attributes whose current and previous value differ. - changed: null, - - // A hash of attributes that have silently changed since the last time - // `change` was called. Will become pending attributes on the next call. - _silent: null, - - // A hash of attributes that have changed since the last `'change'` event - // began. - _pending: null, - - // The default name for the JSON `id` attribute is `"id"`. MongoDB and - // CouchDB users may want to set this to `"_id"`. - idAttribute: 'id', - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // Return a copy of the model's `attributes` object. - toJSON: function(options) { - return _.clone(this.attributes); - }, - - // Get the value of an attribute. - get: function(attr) { - return this.attributes[attr]; - }, - - // Get the HTML-escaped value of an attribute. - escape: function(attr) { - var html; - if (html = this._escapedAttributes[attr]) return html; - var val = this.get(attr); - return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); - }, - - // Returns `true` if the attribute contains a value that is not null - // or undefined. - has: function(attr) { - return this.get(attr) != null; - }, - - // Set a hash of model attributes on the object, firing `"change"` unless - // you choose to silence it. - set: function(key, value, options) { - var attrs, attr, val; - - // Handle both `"key", value` and `{key: value}` -style arguments. - if (_.isObject(key) || key == null) { - attrs = key; - options = value; - } else { - attrs = {}; - attrs[key] = value; - } - - // Extract attributes and options. - options || (options = {}); - if (!attrs) return this; - if (attrs instanceof Model) attrs = attrs.attributes; - if (options.unset) for (attr in attrs) attrs[attr] = void 0; - - // Run validation. - if (!this._validate(attrs, options)) return false; - - // Check for changes of `id`. - if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; - - var changes = options.changes = {}; - var now = this.attributes; - var escaped = this._escapedAttributes; - var prev = this._previousAttributes || {}; - - // For each `set` attribute... - for (attr in attrs) { - val = attrs[attr]; - - // If the new and current value differ, record the change. - if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { - delete escaped[attr]; - (options.silent ? this._silent : changes)[attr] = true; - } - - // Update or delete the current value. - options.unset ? delete now[attr] : now[attr] = val; - - // If the new and previous value differ, record the change. If not, - // then remove changes for this attribute. - if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { - this.changed[attr] = val; - if (!options.silent) this._pending[attr] = true; - } else { - delete this.changed[attr]; - delete this._pending[attr]; - } - } - - // Fire the `"change"` events. - if (!options.silent) this.change(options); - return this; - }, - - // Remove an attribute from the model, firing `"change"` unless you choose - // to silence it. `unset` is a noop if the attribute doesn't exist. - unset: function(attr, options) { - (options || (options = {})).unset = true; - return this.set(attr, null, options); - }, - - // Clear all attributes on the model, firing `"change"` unless you choose - // to silence it. - clear: function(options) { - (options || (options = {})).unset = true; - return this.set(_.clone(this.attributes), options); - }, - - // Fetch the model from the server. If the server's representation of the - // model differs from its current attributes, they will be overriden, - // triggering a `"change"` event. - fetch: function(options) { - options = options ? _.clone(options) : {}; - var model = this; - var success = options.success; - options.success = function(resp, status, xhr) { - if (!model.set(model.parse(resp, xhr), options)) return false; - if (success) success(model, resp); - }; - options.error = Backbone.wrapError(options.error, model, options); - return (this.sync || Backbone.sync).call(this, 'read', this, options); - }, - - // Set a hash of model attributes, and sync the model to the server. - // If the server returns an attributes hash that differs, the model's - // state will be `set` again. - save: function(key, value, options) { - var attrs, current; - - // Handle both `("key", value)` and `({key: value})` -style calls. - if (_.isObject(key) || key == null) { - attrs = key; - options = value; - } else { - attrs = {}; - attrs[key] = value; - } - options = options ? _.clone(options) : {}; - - // If we're "wait"-ing to set changed attributes, validate early. - if (options.wait) { - if (!this._validate(attrs, options)) return false; - current = _.clone(this.attributes); - } - - // Regular saves `set` attributes before persisting to the server. - var silentOptions = _.extend({}, options, {silent: true}); - if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { - return false; - } - - // After a successful server-side save, the client is (optionally) - // updated with the server-side state. - var model = this; - var success = options.success; - options.success = function(resp, status, xhr) { - var serverAttrs = model.parse(resp, xhr); - if (options.wait) { - delete options.wait; - serverAttrs = _.extend(attrs || {}, serverAttrs); - } - if (!model.set(serverAttrs, options)) return false; - if (success) { - success(model, resp); - } else { - model.trigger('sync', model, resp, options); - } - }; - - // Finish configuring and sending the Ajax request. - options.error = Backbone.wrapError(options.error, model, options); - var method = this.isNew() ? 'create' : 'update'; - var xhr = (this.sync || Backbone.sync).call(this, method, this, options); - if (options.wait) this.set(current, silentOptions); - return xhr; - }, - - // Destroy this model on the server if it was already persisted. - // Optimistically removes the model from its collection, if it has one. - // If `wait: true` is passed, waits for the server to respond before removal. - destroy: function(options) { - options = options ? _.clone(options) : {}; - var model = this; - var success = options.success; - - var triggerDestroy = function() { - model.trigger('destroy', model, model.collection, options); - }; - - if (this.isNew()) { - triggerDestroy(); - return false; - } - - options.success = function(resp) { - if (options.wait) triggerDestroy(); - if (success) { - success(model, resp); - } else { - model.trigger('sync', model, resp, options); - } - }; - - options.error = Backbone.wrapError(options.error, model, options); - var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); - if (!options.wait) triggerDestroy(); - return xhr; - }, - - // Default URL for the model's representation on the server -- if you're - // using Backbone's restful methods, override this to change the endpoint - // that will be called. - url: function() { - var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); - if (this.isNew()) return base; - return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); - }, - - // **parse** converts a response into the hash of attributes to be `set` on - // the model. The default implementation is just to pass the response along. - parse: function(resp, xhr) { - return resp; - }, - - // Create a new model with identical attributes to this one. - clone: function() { - return new this.constructor(this.attributes); - }, - - // A model is new if it has never been saved to the server, and lacks an id. - isNew: function() { - return this.id == null; - }, - - // Call this method to manually fire a `"change"` event for this model and - // a `"change:attribute"` event for each changed attribute. - // Calling this will cause all objects observing the model to update. - change: function(options) { - options || (options = {}); - var changing = this._changing; - this._changing = true; - - // Silent changes become pending changes. - for (var attr in this._silent) this._pending[attr] = true; - - // Silent changes are triggered. - var changes = _.extend({}, options.changes, this._silent); - this._silent = {}; - for (var attr in changes) { - this.trigger('change:' + attr, this, this.get(attr), options); - } - if (changing) return this; - - // Continue firing `"change"` events while there are pending changes. - while (!_.isEmpty(this._pending)) { - this._pending = {}; - this.trigger('change', this, options); - // Pending and silent changes still remain. - for (var attr in this.changed) { - if (this._pending[attr] || this._silent[attr]) continue; - delete this.changed[attr]; - } - this._previousAttributes = _.clone(this.attributes); - } - - this._changing = false; - return this; - }, - - // Determine if the model has changed since the last `"change"` event. - // If you specify an attribute name, determine if that attribute has changed. - hasChanged: function(attr) { - if (!arguments.length) return !_.isEmpty(this.changed); - return _.has(this.changed, attr); - }, - - // Return an object containing all the attributes that have changed, or - // false if there are no changed attributes. Useful for determining what - // parts of a view need to be updated and/or what attributes need to be - // persisted to the server. Unset attributes will be set to undefined. - // You can also pass an attributes object to diff against the model, - // determining if there *would be* a change. - changedAttributes: function(diff) { - if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; - var val, changed = false, old = this._previousAttributes; - for (var attr in diff) { - if (_.isEqual(old[attr], (val = diff[attr]))) continue; - (changed || (changed = {}))[attr] = val; - } - return changed; - }, - - // Get the previous value of an attribute, recorded at the time the last - // `"change"` event was fired. - previous: function(attr) { - if (!arguments.length || !this._previousAttributes) return null; - return this._previousAttributes[attr]; - }, - - // Get all of the attributes of the model at the time of the previous - // `"change"` event. - previousAttributes: function() { - return _.clone(this._previousAttributes); - }, - - // Check if the model is currently in a valid state. It's only possible to - // get into an *invalid* state if you're using silent changes. - isValid: function() { - return !this.validate(this.attributes); - }, - - // Run validation against the next complete set of model attributes, - // returning `true` if all is well. If a specific `error` callback has - // been passed, call that instead of firing the general `"error"` event. - _validate: function(attrs, options) { - if (options.silent || !this.validate) return true; - attrs = _.extend({}, this.attributes, attrs); - var error = this.validate(attrs, options); - if (!error) return true; - if (options && options.error) { - options.error(this, error, options); - } else { - this.trigger('error', this, error, options); - } - return false; - } - - }); - - // Backbone.Collection - // ------------------- - - // Provides a standard collection class for our sets of models, ordered - // or unordered. If a `comparator` is specified, the Collection will maintain - // its models in sort order, as they're added and removed. - var Collection = Backbone.Collection = function(models, options) { - options || (options = {}); - if (options.model) this.model = options.model; - if (options.comparator) this.comparator = options.comparator; - this._reset(); - this.initialize.apply(this, arguments); - if (models) this.reset(models, {silent: true, parse: options.parse}); - }; - - // Define the Collection's inheritable methods. - _.extend(Collection.prototype, Events, { - - // The default model for a collection is just a **Backbone.Model**. - // This should be overridden in most cases. - model: Model, - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // The JSON representation of a Collection is an array of the - // models' attributes. - toJSON: function(options) { - return this.map(function(model){ return model.toJSON(options); }); - }, - - // Add a model, or list of models to the set. Pass **silent** to avoid - // firing the `add` event for every new model. - add: function(models, options) { - var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; - options || (options = {}); - models = _.isArray(models) ? models.slice() : [models]; - - // Begin by turning bare objects into model references, and preventing - // invalid models or duplicate models from being added. - for (i = 0, length = models.length; i < length; i++) { - if (!(model = models[i] = this._prepareModel(models[i], options))) { - throw new Error("Can't add an invalid model to a collection"); - } - cid = model.cid; - id = model.id; - if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { - dups.push(i); - continue; - } - cids[cid] = ids[id] = model; - } - - // Remove duplicates. - i = dups.length; - while (i--) { - models.splice(dups[i], 1); - } - - // Listen to added models' events, and index models for lookup by - // `id` and by `cid`. - for (i = 0, length = models.length; i < length; i++) { - (model = models[i]).on('all', this._onModelEvent, this); - this._byCid[model.cid] = model; - if (model.id != null) this._byId[model.id] = model; - } - - // Insert models into the collection, re-sorting if needed, and triggering - // `add` events unless silenced. - this.length += length; - index = options.at != null ? options.at : this.models.length; - splice.apply(this.models, [index, 0].concat(models)); - if (this.comparator) this.sort({silent: true}); - if (options.silent) return this; - for (i = 0, length = this.models.length; i < length; i++) { - if (!cids[(model = this.models[i]).cid]) continue; - options.index = i; - model.trigger('add', model, this, options); - } - return this; - }, - - // Remove a model, or a list of models from the set. Pass silent to avoid - // firing the `remove` event for every model removed. - remove: function(models, options) { - var i, l, index, model; - options || (options = {}); - models = _.isArray(models) ? models.slice() : [models]; - for (i = 0, l = models.length; i < l; i++) { - model = this.getByCid(models[i]) || this.get(models[i]); - if (!model) continue; - delete this._byId[model.id]; - delete this._byCid[model.cid]; - index = this.indexOf(model); - this.models.splice(index, 1); - this.length--; - if (!options.silent) { - options.index = index; - model.trigger('remove', model, this, options); - } - this._removeReference(model); - } - return this; - }, - - // Add a model to the end of the collection. - push: function(model, options) { - model = this._prepareModel(model, options); - this.add(model, options); - return model; - }, - - // Remove a model from the end of the collection. - pop: function(options) { - var model = this.at(this.length - 1); - this.remove(model, options); - return model; - }, - - // Add a model to the beginning of the collection. - unshift: function(model, options) { - model = this._prepareModel(model, options); - this.add(model, _.extend({at: 0}, options)); - return model; - }, - - // Remove a model from the beginning of the collection. - shift: function(options) { - var model = this.at(0); - this.remove(model, options); - return model; - }, - - // Get a model from the set by id. - get: function(id) { - if (id == null) return void 0; - return this._byId[id.id != null ? id.id : id]; - }, - - // Get a model from the set by client id. - getByCid: function(cid) { - return cid && this._byCid[cid.cid || cid]; - }, - - // Get the model at the given index. - at: function(index) { - return this.models[index]; - }, - - // Return models with matching attributes. Useful for simple cases of `filter`. - where: function(attrs) { - if (_.isEmpty(attrs)) return []; - return this.filter(function(model) { - for (var key in attrs) { - if (attrs[key] !== model.get(key)) return false; - } - return true; - }); - }, - - // Force the collection to re-sort itself. You don't need to call this under - // normal circumstances, as the set will maintain sort order as each item - // is added. - sort: function(options) { - options || (options = {}); - if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); - var boundComparator = _.bind(this.comparator, this); - if (this.comparator.length == 1) { - this.models = this.sortBy(boundComparator); - } else { - this.models.sort(boundComparator); - } - if (!options.silent) this.trigger('reset', this, options); - return this; - }, - - // Pluck an attribute from each model in the collection. - pluck: function(attr) { - return _.map(this.models, function(model){ return model.get(attr); }); - }, - - // When you have more items than you want to add or remove individually, - // you can reset the entire set with a new list of models, without firing - // any `add` or `remove` events. Fires `reset` when finished. - reset: function(models, options) { - models || (models = []); - options || (options = {}); - for (var i = 0, l = this.models.length; i < l; i++) { - this._removeReference(this.models[i]); - } - this._reset(); - this.add(models, _.extend({silent: true}, options)); - if (!options.silent) this.trigger('reset', this, options); - return this; - }, - - // Fetch the default set of models for this collection, resetting the - // collection when they arrive. If `add: true` is passed, appends the - // models to the collection instead of resetting. - fetch: function(options) { - options = options ? _.clone(options) : {}; - if (options.parse === undefined) options.parse = true; - var collection = this; - var success = options.success; - options.success = function(resp, status, xhr) { - collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); - if (success) success(collection, resp); - }; - options.error = Backbone.wrapError(options.error, collection, options); - return (this.sync || Backbone.sync).call(this, 'read', this, options); - }, - - // Create a new instance of a model in this collection. Add the model to the - // collection immediately, unless `wait: true` is passed, in which case we - // wait for the server to agree. - create: function(model, options) { - var coll = this; - options = options ? _.clone(options) : {}; - model = this._prepareModel(model, options); - if (!model) return false; - if (!options.wait) coll.add(model, options); - var success = options.success; - options.success = function(nextModel, resp, xhr) { - if (options.wait) coll.add(nextModel, options); - if (success) { - success(nextModel, resp); - } else { - nextModel.trigger('sync', model, resp, options); - } - }; - model.save(null, options); - return model; - }, - - // **parse** converts a response into a list of models to be added to the - // collection. The default implementation is just to pass it through. - parse: function(resp, xhr) { - return resp; - }, - - // Proxy to _'s chain. Can't be proxied the same way the rest of the - // underscore methods are proxied because it relies on the underscore - // constructor. - chain: function () { - return _(this.models).chain(); - }, - - // Reset all internal state. Called when the collection is reset. - _reset: function(options) { - this.length = 0; - this.models = []; - this._byId = {}; - this._byCid = {}; - }, - - // Prepare a model or hash of attributes to be added to this collection. - _prepareModel: function(model, options) { - options || (options = {}); - if (!(model instanceof Model)) { - var attrs = model; - options.collection = this; - model = new this.model(attrs, options); - if (!model._validate(model.attributes, options)) model = false; - } else if (!model.collection) { - model.collection = this; - } - return model; - }, - - // Internal method to remove a model's ties to a collection. - _removeReference: function(model) { - if (this == model.collection) { - delete model.collection; - } - model.off('all', this._onModelEvent, this); - }, - - // Internal method called every time a model in the set fires an event. - // Sets need to update their indexes when models change ids. All other - // events simply proxy through. "add" and "remove" events that originate - // in other collections are ignored. - _onModelEvent: function(event, model, collection, options) { - if ((event == 'add' || event == 'remove') && collection != this) return; - if (event == 'destroy') { - this.remove(model, options); - } - if (model && event === 'change:' + model.idAttribute) { - delete this._byId[model.previous(model.idAttribute)]; - this._byId[model.id] = model; - } - this.trigger.apply(this, arguments); - } - - }); - - // Underscore methods that we want to implement on the Collection. - var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', - 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', - 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', - 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', - 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; - - // Mix in each Underscore method as a proxy to `Collection#models`. - _.each(methods, function(method) { - Collection.prototype[method] = function() { - return _[method].apply(_, [this.models].concat(_.toArray(arguments))); - }; - }); - - // Backbone.Router - // ------------------- - - // Routers map faux-URLs to actions, and fire events when routes are - // matched. Creating a new one sets its `routes` hash, if not set statically. - var Router = Backbone.Router = function(options) { - options || (options = {}); - if (options.routes) this.routes = options.routes; - this._bindRoutes(); - this.initialize.apply(this, arguments); - }; - - // Cached regular expressions for matching named param parts and splatted - // parts of route strings. - var namedParam = /:\w+/g; - var splatParam = /\*\w+/g; - var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; - - // Set up all inheritable **Backbone.Router** properties and methods. - _.extend(Router.prototype, Events, { - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // Manually bind a single named route to a callback. For example: - // - // this.route('search/:query/p:num', 'search', function(query, num) { - // ... - // }); - // - route: function(route, name, callback) { - Backbone.history || (Backbone.history = new History); - if (!_.isRegExp(route)) route = this._routeToRegExp(route); - if (!callback) callback = this[name]; - Backbone.history.route(route, _.bind(function(fragment) { - var args = this._extractParameters(route, fragment); - callback && callback.apply(this, args); - this.trigger.apply(this, ['route:' + name].concat(args)); - Backbone.history.trigger('route', this, name, args); - }, this)); - return this; - }, - - // Simple proxy to `Backbone.history` to save a fragment into the history. - navigate: function(fragment, options) { - Backbone.history.navigate(fragment, options); - }, - - // Bind all defined routes to `Backbone.history`. We have to reverse the - // order of the routes here to support behavior where the most general - // routes can be defined at the bottom of the route map. - _bindRoutes: function() { - if (!this.routes) return; - var routes = []; - for (var route in this.routes) { - routes.unshift([route, this.routes[route]]); - } - for (var i = 0, l = routes.length; i < l; i++) { - this.route(routes[i][0], routes[i][1], this[routes[i][1]]); - } - }, - - // Convert a route string into a regular expression, suitable for matching - // against the current location hash. - _routeToRegExp: function(route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(namedParam, '([^\/]+)') - .replace(splatParam, '(.*?)'); - return new RegExp('^' + route + '$'); - }, - - // Given a route, and a URL fragment that it matches, return the array of - // extracted parameters. - _extractParameters: function(route, fragment) { - return route.exec(fragment).slice(1); - } - - }); - - // Backbone.History - // ---------------- - - // Handles cross-browser history management, based on URL fragments. If the - // browser does not support `onhashchange`, falls back to polling. - var History = Backbone.History = function() { - this.handlers = []; - _.bindAll(this, 'checkUrl'); - }; - - // Cached regex for cleaning leading hashes and slashes . - var routeStripper = /^[#\/]/; - - // Cached regex for detecting MSIE. - var isExplorer = /msie [\w.]+/; - - // Has the history handling already been started? - History.started = false; - - // Set up all inheritable **Backbone.History** properties and methods. - _.extend(History.prototype, Events, { - - // The default interval to poll for hash changes, if necessary, is - // twenty times a second. - interval: 50, - - // Gets the true hash value. Cannot use location.hash directly due to bug - // in Firefox where location.hash will always be decoded. - getHash: function(windowOverride) { - var loc = windowOverride ? windowOverride.location : window.location; - var match = loc.href.match(/#(.*)$/); - return match ? match[1] : ''; - }, - - // Get the cross-browser normalized URL fragment, either from the URL, - // the hash, or the override. - getFragment: function(fragment, forcePushState) { - if (fragment == null) { - if (this._hasPushState || forcePushState) { - fragment = window.location.pathname; - var search = window.location.search; - if (search) fragment += search; - } else { - fragment = this.getHash(); - } - } - if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); - return fragment.replace(routeStripper, ''); - }, - - // Start the hash change handling, returning `true` if the current URL matches - // an existing route, and `false` otherwise. - start: function(options) { - if (History.started) throw new Error("Backbone.history has already been started"); - History.started = true; - - // Figure out the initial configuration. Do we need an iframe? - // Is pushState desired ... is it available? - this.options = _.extend({}, {root: '/'}, this.options, options); - this._wantsHashChange = this.options.hashChange !== false; - this._wantsPushState = !!this.options.pushState; - this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); - var fragment = this.getFragment(); - var docMode = document.documentMode; - var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); - - if (oldIE) { - this.iframe = $('