PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/static/scripts/libs/backbone/backbone-relational.js

https://bitbucket.org/james_taylor/galaxy-webapp-refactoring
JavaScript | 1668 lines | 1092 code | 236 blank | 340 comment | 266 complexity | de629e389d4cedb477313086dab8669c MD5 | raw file
  1. /**
  2. * Backbone-relational.js 0.5.0
  3. * (c) 2011 Paul Uithol
  4. *
  5. * Backbone-relational may be freely distributed under the MIT license.
  6. * For details and documentation: https://github.com/PaulUithol/Backbone-relational.
  7. * Depends on Backbone: https://github.com/documentcloud/backbone.
  8. */
  9. ( function( undefined ) {
  10. "use strict";
  11. /**
  12. * CommonJS shim
  13. **/
  14. var _, Backbone, exports;
  15. if ( typeof window === 'undefined' ) {
  16. _ = require( 'underscore' );
  17. Backbone = require( 'backbone' );
  18. exports = module.exports = Backbone;
  19. }
  20. else {
  21. _ = window._;
  22. Backbone = window.Backbone;
  23. exports = window;
  24. }
  25. Backbone.Relational = {
  26. showWarnings: true
  27. };
  28. /**
  29. * Semaphore mixin; can be used as both binary and counting.
  30. **/
  31. Backbone.Semaphore = {
  32. _permitsAvailable: null,
  33. _permitsUsed: 0,
  34. acquire: function() {
  35. if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) {
  36. throw new Error( 'Max permits acquired' );
  37. }
  38. else {
  39. this._permitsUsed++;
  40. }
  41. },
  42. release: function() {
  43. if ( this._permitsUsed === 0 ) {
  44. throw new Error( 'All permits released' );
  45. }
  46. else {
  47. this._permitsUsed--;
  48. }
  49. },
  50. isLocked: function() {
  51. return this._permitsUsed > 0;
  52. },
  53. setAvailablePermits: function( amount ) {
  54. if ( this._permitsUsed > amount ) {
  55. throw new Error( 'Available permits cannot be less than used permits' );
  56. }
  57. this._permitsAvailable = amount;
  58. }
  59. };
  60. /**
  61. * A BlockingQueue that accumulates items while blocked (via 'block'),
  62. * and processes them when unblocked (via 'unblock').
  63. * Process can also be called manually (via 'process').
  64. */
  65. Backbone.BlockingQueue = function() {
  66. this._queue = [];
  67. };
  68. _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, {
  69. _queue: null,
  70. add: function( func ) {
  71. if ( this.isBlocked() ) {
  72. this._queue.push( func );
  73. }
  74. else {
  75. func();
  76. }
  77. },
  78. process: function() {
  79. while ( this._queue && this._queue.length ) {
  80. this._queue.shift()();
  81. }
  82. },
  83. block: function() {
  84. this.acquire();
  85. },
  86. unblock: function() {
  87. this.release();
  88. if ( !this.isBlocked() ) {
  89. this.process();
  90. }
  91. },
  92. isBlocked: function() {
  93. return this.isLocked();
  94. }
  95. });
  96. /**
  97. * Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'update:<key>')
  98. * until the top-level object is fully initialized (see 'Backbone.RelationalModel').
  99. */
  100. Backbone.Relational.eventQueue = new Backbone.BlockingQueue();
  101. /**
  102. * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel.
  103. * Handles lookup for relations.
  104. */
  105. Backbone.Store = function() {
  106. this._collections = [];
  107. this._reverseRelations = [];
  108. this._subModels = [];
  109. this._modelScopes = [ exports ];
  110. };
  111. _.extend( Backbone.Store.prototype, Backbone.Events, {
  112. addModelScope: function( scope ) {
  113. this._modelScopes.push( scope );
  114. },
  115. /**
  116. * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel'
  117. * for a model later in 'setupSuperModel'.
  118. *
  119. * @param {Backbone.RelationalModel} subModelTypes
  120. * @param {Backbone.RelationalModel} superModelType
  121. */
  122. addSubModels: function( subModelTypes, superModelType ) {
  123. this._subModels.push({
  124. 'superModelType': superModelType,
  125. 'subModels': subModelTypes
  126. });
  127. },
  128. /**
  129. * Check if the given modelType is registered as another model's subModel. If so, add it to the super model's
  130. * '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'.
  131. *
  132. * @param {Backbone.RelationalModel} modelType
  133. */
  134. setupSuperModel: function( modelType ) {
  135. _.find( this._subModels, function( subModelDef ) {
  136. return _.find( subModelDef.subModels, function( subModelTypeName, typeValue ) {
  137. var subModelType = this.getObjectByName( subModelTypeName );
  138. if ( modelType === subModelType ) {
  139. // Set 'modelType' as a child of the found superModel
  140. subModelDef.superModelType._subModels[ typeValue ] = modelType;
  141. // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'.
  142. modelType._superModel = subModelDef.superModelType;
  143. modelType._subModelTypeValue = typeValue;
  144. modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute;
  145. return true;
  146. }
  147. }, this );
  148. }, this );
  149. },
  150. /**
  151. * Add a reverse relation. Is added to the 'relations' property on model's prototype, and to
  152. * existing instances of 'model' in the store as well.
  153. * @param {Object} relation
  154. * @param {Backbone.RelationalModel} relation.model
  155. * @param {String} relation.type
  156. * @param {String} relation.key
  157. * @param {String|Object} relation.relatedModel
  158. */
  159. addReverseRelation: function( relation ) {
  160. var exists = _.any( this._reverseRelations, function( rel ) {
  161. return _.all( relation, function( val, key ) {
  162. return val === rel[ key ];
  163. });
  164. });
  165. if ( !exists && relation.model && relation.type ) {
  166. this._reverseRelations.push( relation );
  167. var addRelation = function( model, relation ) {
  168. if ( !model.prototype.relations ) {
  169. model.prototype.relations = [];
  170. }
  171. model.prototype.relations.push( relation );
  172. _.each( model._subModels, function( subModel ) {
  173. addRelation( subModel, relation );
  174. }, this );
  175. };
  176. addRelation( relation.model, relation );
  177. this.retroFitRelation( relation );
  178. }
  179. },
  180. /**
  181. * Add a 'relation' to all existing instances of 'relation.model' in the store
  182. * @param {Object} relation
  183. */
  184. retroFitRelation: function( relation ) {
  185. var coll = this.getCollection( relation.model );
  186. coll.each( function( model ) {
  187. if ( !( model instanceof relation.model ) ) {
  188. return;
  189. }
  190. new relation.type( model, relation );
  191. }, this);
  192. },
  193. /**
  194. * Find the Store's collection for a certain type of model.
  195. * @param {Backbone.RelationalModel} model
  196. * @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
  197. */
  198. getCollection: function( model ) {
  199. if ( model instanceof Backbone.RelationalModel ) {
  200. model = model.constructor;
  201. }
  202. var rootModel = model;
  203. while ( rootModel._superModel ) {
  204. rootModel = rootModel._superModel;
  205. }
  206. var coll = _.detect( this._collections, function( c ) {
  207. return c.model === rootModel;
  208. });
  209. if ( !coll ) {
  210. coll = this._createCollection( model );
  211. }
  212. return coll;
  213. },
  214. /**
  215. * Find a type on the global object by name. Splits name on dots.
  216. * @param {String} name
  217. * @return {Object}
  218. */
  219. getObjectByName: function( name ) {
  220. var parts = name.split( '.' ),
  221. type = null;
  222. _.find( this._modelScopes, function( scope ) {
  223. type = _.reduce( parts, function( memo, val ) {
  224. return memo[ val ];
  225. }, scope );
  226. if ( type && type !== scope ) {
  227. return true;
  228. }
  229. }, this );
  230. return type;
  231. },
  232. _createCollection: function( type ) {
  233. var coll;
  234. // If 'type' is an instance, take its constructor
  235. if ( type instanceof Backbone.RelationalModel ) {
  236. type = type.constructor;
  237. }
  238. // Type should inherit from Backbone.RelationalModel.
  239. if ( type.prototype instanceof Backbone.RelationalModel ) {
  240. coll = new Backbone.Collection();
  241. coll.model = type;
  242. this._collections.push( coll );
  243. }
  244. return coll;
  245. },
  246. /**
  247. * Find the attribute that is to be used as the `id` on a given object
  248. * @param type
  249. * @param {String|Number|Object|Backbone.RelationalModel} item
  250. */
  251. resolveIdForItem: function( type, item ) {
  252. var id = _.isString( item ) || _.isNumber( item ) ? item : null;
  253. if ( id == null ) {
  254. if ( item instanceof Backbone.RelationalModel ) {
  255. id = item.id;
  256. }
  257. else if ( _.isObject( item ) ) {
  258. id = item[ type.prototype.idAttribute ];
  259. }
  260. }
  261. return id;
  262. },
  263. /**
  264. *
  265. * @param type
  266. * @param {String|Number|Object|Backbone.RelationalModel} item
  267. */
  268. find: function( type, item ) {
  269. var id = this.resolveIdForItem( type, item );
  270. var coll = this.getCollection( type );
  271. // Because the found object could be of any of the type's superModel
  272. // types, only return it if it's actually of the type asked for.
  273. if ( coll ) {
  274. var obj = coll.get( id );
  275. if ( obj instanceof type ) {
  276. return obj;
  277. }
  278. }
  279. return null;
  280. },
  281. /**
  282. * Add a 'model' to it's appropriate collection. Retain the original contents of 'model.collection'.
  283. * @param {Backbone.RelationalModel} model
  284. */
  285. register: function( model ) {
  286. var modelColl = model.collection;
  287. var coll = this.getCollection( model );
  288. coll && coll.add( model );
  289. model.bind( 'destroy', this.unregister, this );
  290. model.collection = modelColl;
  291. },
  292. /**
  293. * Explicitly update a model's id in it's store collection
  294. * @param {Backbone.RelationalModel} model
  295. */
  296. update: function( model ) {
  297. var coll = this.getCollection( model );
  298. coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
  299. },
  300. /**
  301. * Remove a 'model' from the store.
  302. * @param {Backbone.RelationalModel} model
  303. */
  304. unregister: function( model ) {
  305. model.unbind( 'destroy', this.unregister );
  306. var coll = this.getCollection( model );
  307. coll && coll.remove( model );
  308. }
  309. });
  310. Backbone.Relational.store = new Backbone.Store();
  311. /**
  312. * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events
  313. * are used to regulate addition and removal of models from relations.
  314. *
  315. * @param {Backbone.RelationalModel} instance
  316. * @param {Object} options
  317. * @param {string} options.key
  318. * @param {Backbone.RelationalModel.constructor} options.relatedModel
  319. * @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids.
  320. * @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store.
  321. * @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate
  322. * the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs
  323. * {Backbone.Relation|String} type ('HasOne' or 'HasMany').
  324. */
  325. Backbone.Relation = function( instance, options ) {
  326. this.instance = instance;
  327. // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype
  328. options = _.isObject( options ) ? options : {};
  329. this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation );
  330. this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type :
  331. Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type );
  332. this.model = options.model || this.instance.constructor;
  333. this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options );
  334. this.key = this.options.key;
  335. this.keySource = this.options.keySource || this.key;
  336. this.keyDestination = this.options.keyDestination || this.keySource || this.key;
  337. // 'exports' should be the global object where 'relatedModel' can be found on if given as a string.
  338. this.relatedModel = this.options.relatedModel;
  339. if ( _.isString( this.relatedModel ) ) {
  340. this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel );
  341. }
  342. if ( !this.checkPreconditions() ) {
  343. return false;
  344. }
  345. if ( instance ) {
  346. this.keyContents = this.instance.get( this.keySource );
  347. // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
  348. if ( this.key !== this.keySource ) {
  349. this.instance.unset( this.keySource, { silent: true } );
  350. }
  351. // Add this Relation to instance._relations
  352. this.instance._relations.push( this );
  353. }
  354. // Add the reverse relation on 'relatedModel' to the store's reverseRelations
  355. if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) {
  356. Backbone.Relational.store.addReverseRelation( _.defaults( {
  357. isAutoRelation: true,
  358. model: this.relatedModel,
  359. relatedModel: this.model,
  360. reverseRelation: this.options // current relation is the 'reverseRelation' for it's own reverseRelation
  361. },
  362. this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
  363. ) );
  364. }
  365. _.bindAll( this, '_modelRemovedFromCollection', '_relatedModelAdded', '_relatedModelRemoved' );
  366. if ( instance ) {
  367. this.initialize();
  368. // When a model in the store is destroyed, check if it is 'this.instance'.
  369. Backbone.Relational.store.getCollection( this.instance )
  370. .bind( 'relational:remove', this._modelRemovedFromCollection );
  371. // When 'relatedModel' are created or destroyed, check if it affects this relation.
  372. Backbone.Relational.store.getCollection( this.relatedModel )
  373. .bind( 'relational:add', this._relatedModelAdded )
  374. .bind( 'relational:remove', this._relatedModelRemoved );
  375. }
  376. };
  377. // Fix inheritance :\
  378. Backbone.Relation.extend = Backbone.Model.extend;
  379. // Set up all inheritable **Backbone.Relation** properties and methods.
  380. _.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, {
  381. options: {
  382. createModels: true,
  383. includeInJSON: true,
  384. isAutoRelation: false
  385. },
  386. instance: null,
  387. key: null,
  388. keyContents: null,
  389. relatedModel: null,
  390. reverseRelation: null,
  391. related: null,
  392. _relatedModelAdded: function( model, coll, options ) {
  393. // Allow 'model' to set up it's relations, before calling 'tryAddRelated'
  394. // (which can result in a call to 'addRelated' on a relation of 'model')
  395. var dit = this;
  396. model.queue( function() {
  397. dit.tryAddRelated( model, options );
  398. });
  399. },
  400. _relatedModelRemoved: function( model, coll, options ) {
  401. this.removeRelated( model, options );
  402. },
  403. _modelRemovedFromCollection: function( model ) {
  404. if ( model === this.instance ) {
  405. this.destroy();
  406. }
  407. },
  408. /**
  409. * Check several pre-conditions.
  410. * @return {Boolean} True if pre-conditions are satisfied, false if they're not.
  411. */
  412. checkPreconditions: function() {
  413. var i = this.instance,
  414. k = this.key,
  415. m = this.model,
  416. rm = this.relatedModel,
  417. warn = Backbone.Relational.showWarnings && typeof console !== 'undefined';
  418. if ( !m || !k || !rm ) {
  419. warn && console.warn( 'Relation=%o; no model, key or relatedModel (%o, %o, %o)', this, m, k, rm );
  420. return false;
  421. }
  422. // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
  423. if ( !( m.prototype instanceof Backbone.RelationalModel ) ) {
  424. warn && console.warn( 'Relation=%o; model does not inherit from Backbone.RelationalModel (%o)', this, i );
  425. return false;
  426. }
  427. // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
  428. if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) {
  429. warn && console.warn( 'Relation=%o; relatedModel does not inherit from Backbone.RelationalModel (%o)', this, rm );
  430. return false;
  431. }
  432. // Check if this is not a HasMany, and the reverse relation is HasMany as well
  433. if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) {
  434. warn && console.warn( 'Relation=%o; relation is a HasMany, and the reverseRelation is HasMany as well.', this );
  435. return false;
  436. }
  437. // Check if we're not attempting to create a duplicate relationship
  438. if ( i && i._relations.length ) {
  439. var exists = _.any( i._relations, function( rel ) {
  440. var hasReverseRelation = this.reverseRelation.key && rel.reverseRelation.key;
  441. return rel.relatedModel === rm && rel.key === k &&
  442. ( !hasReverseRelation || this.reverseRelation.key === rel.reverseRelation.key );
  443. }, this );
  444. if ( exists ) {
  445. warn && console.warn( 'Relation=%o between instance=%o.%s and relatedModel=%o.%s already exists',
  446. this, i, k, rm, this.reverseRelation.key );
  447. return false;
  448. }
  449. }
  450. return true;
  451. },
  452. /**
  453. * Set the related model(s) for this relation
  454. * @param {Backbone.Mode|Backbone.Collection} related
  455. * @param {Object} [options]
  456. */
  457. setRelated: function( related, options ) {
  458. this.related = related;
  459. this.instance.acquire();
  460. this.instance.set( this.key, related, _.defaults( options || {}, { silent: true } ) );
  461. this.instance.release();
  462. },
  463. /**
  464. * Determine if a relation (on a different RelationalModel) is the reverse
  465. * relation of the current one.
  466. * @param {Backbone.Relation} relation
  467. * @return {Boolean}
  468. */
  469. _isReverseRelation: function( relation ) {
  470. if ( relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
  471. this.key === relation.reverseRelation.key ) {
  472. return true;
  473. }
  474. return false;
  475. },
  476. /**
  477. * Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
  478. * @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model.
  479. * If not specified, 'this.related' is used.
  480. * @return {Backbone.Relation[]}
  481. */
  482. getReverseRelations: function( model ) {
  483. var reverseRelations = [];
  484. // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array.
  485. var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] );
  486. _.each( models , function( related ) {
  487. _.each( related.getRelations(), function( relation ) {
  488. if ( this._isReverseRelation( relation ) ) {
  489. reverseRelations.push( relation );
  490. }
  491. }, this );
  492. }, this );
  493. return reverseRelations;
  494. },
  495. /**
  496. * Rename options.silent to options.silentChange, so events propagate properly.
  497. * (for example in HasMany, from 'addRelated'->'handleAddition')
  498. * @param {Object} [options]
  499. * @return {Object}
  500. */
  501. sanitizeOptions: function( options ) {
  502. options = options ? _.clone( options ) : {};
  503. if ( options.silent ) {
  504. options.silentChange = true;
  505. delete options.silent;
  506. }
  507. return options;
  508. },
  509. /**
  510. * Rename options.silentChange to options.silent, so events are silenced as intended in Backbone's
  511. * original functions.
  512. * @param {Object} [options]
  513. * @return {Object}
  514. */
  515. unsanitizeOptions: function( options ) {
  516. options = options ? _.clone( options ) : {};
  517. if ( options.silentChange ) {
  518. options.silent = true;
  519. delete options.silentChange;
  520. }
  521. return options;
  522. },
  523. // Cleanup. Get reverse relation, call removeRelated on each.
  524. destroy: function() {
  525. Backbone.Relational.store.getCollection( this.instance )
  526. .unbind( 'relational:remove', this._modelRemovedFromCollection );
  527. Backbone.Relational.store.getCollection( this.relatedModel )
  528. .unbind( 'relational:add', this._relatedModelAdded )
  529. .unbind( 'relational:remove', this._relatedModelRemoved );
  530. _.each( this.getReverseRelations(), function( relation ) {
  531. relation.removeRelated( this.instance );
  532. }, this );
  533. }
  534. });
  535. Backbone.HasOne = Backbone.Relation.extend({
  536. options: {
  537. reverseRelation: { type: 'HasMany' }
  538. },
  539. initialize: function() {
  540. _.bindAll( this, 'onChange' );
  541. this.instance.bind( 'relational:change:' + this.key, this.onChange );
  542. var model = this.findRelated( { silent: true } );
  543. this.setRelated( model );
  544. // Notify new 'related' object of the new relation.
  545. _.each( this.getReverseRelations(), function( relation ) {
  546. relation.addRelated( this.instance );
  547. }, this );
  548. },
  549. findRelated: function( options ) {
  550. var item = this.keyContents;
  551. var model = null;
  552. if ( item instanceof this.relatedModel ) {
  553. model = item;
  554. }
  555. else if ( item ) {
  556. model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } );
  557. }
  558. return model;
  559. },
  560. /**
  561. * If the key is changed, notify old & new reverse relations and initialize the new relation
  562. */
  563. onChange: function( model, attr, options ) {
  564. // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
  565. if ( this.isLocked() ) {
  566. return;
  567. }
  568. this.acquire();
  569. options = this.sanitizeOptions( options );
  570. // 'options._related' is set by 'addRelated'/'removeRelated'. If it is set, the change
  571. // is the result of a call from a relation. If it's not, the change is the result of
  572. // a 'set' call on this.instance.
  573. var changed = _.isUndefined( options._related );
  574. var oldRelated = changed ? this.related : options._related;
  575. if ( changed ) {
  576. this.keyContents = attr;
  577. // Set new 'related'
  578. if ( attr instanceof this.relatedModel ) {
  579. this.related = attr;
  580. }
  581. else if ( attr ) {
  582. var related = this.findRelated( options );
  583. this.setRelated( related );
  584. }
  585. else {
  586. this.setRelated( null );
  587. }
  588. }
  589. // Notify old 'related' object of the terminated relation
  590. if ( oldRelated && this.related !== oldRelated ) {
  591. _.each( this.getReverseRelations( oldRelated ), function( relation ) {
  592. relation.removeRelated( this.instance, options );
  593. }, this );
  594. }
  595. // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
  596. // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
  597. // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
  598. _.each( this.getReverseRelations(), function( relation ) {
  599. relation.addRelated( this.instance, options );
  600. }, this);
  601. // Fire the 'update:<key>' event if 'related' was updated
  602. if ( !options.silentChange && this.related !== oldRelated ) {
  603. var dit = this;
  604. Backbone.Relational.eventQueue.add( function() {
  605. dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options );
  606. });
  607. }
  608. this.release();
  609. },
  610. /**
  611. * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
  612. */
  613. tryAddRelated: function( model, options ) {
  614. if ( this.related ) {
  615. return;
  616. }
  617. options = this.sanitizeOptions( options );
  618. var item = this.keyContents;
  619. if ( item ) {
  620. var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
  621. if ( model.id === id ) {
  622. this.addRelated( model, options );
  623. }
  624. }
  625. },
  626. addRelated: function( model, options ) {
  627. if ( model !== this.related ) {
  628. var oldRelated = this.related || null;
  629. this.setRelated( model );
  630. this.onChange( this.instance, model, { _related: oldRelated } );
  631. }
  632. },
  633. removeRelated: function( model, options ) {
  634. if ( !this.related ) {
  635. return;
  636. }
  637. if ( model === this.related ) {
  638. var oldRelated = this.related || null;
  639. this.setRelated( null );
  640. this.onChange( this.instance, model, { _related: oldRelated } );
  641. }
  642. }
  643. });
  644. Backbone.HasMany = Backbone.Relation.extend({
  645. collectionType: null,
  646. options: {
  647. reverseRelation: { type: 'HasOne' },
  648. collectionType: Backbone.Collection,
  649. collectionKey: true,
  650. collectionOptions: {}
  651. },
  652. initialize: function() {
  653. _.bindAll( this, 'onChange', 'handleAddition', 'handleRemoval', 'handleReset' );
  654. this.instance.bind( 'relational:change:' + this.key, this.onChange );
  655. // Handle a custom 'collectionType'
  656. this.collectionType = this.options.collectionType;
  657. if ( _.isString( this.collectionType ) ) {
  658. this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType );
  659. }
  660. if ( !this.collectionType.prototype instanceof Backbone.Collection ){
  661. throw new Error( 'collectionType must inherit from Backbone.Collection' );
  662. }
  663. // Handle cases where a model/relation is created with a collection passed straight into 'attributes'
  664. if ( this.keyContents instanceof Backbone.Collection ) {
  665. this.setRelated( this._prepareCollection( this.keyContents ) );
  666. }
  667. else {
  668. this.setRelated( this._prepareCollection() );
  669. }
  670. this.findRelated( { silent: true } );
  671. },
  672. _getCollectionOptions: function() {
  673. return _.isFunction( this.options.collectionOptions ) ?
  674. this.options.collectionOptions( this.instance ) :
  675. this.options.collectionOptions;
  676. },
  677. /**
  678. * Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany.
  679. * If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option.
  680. * @param {Backbone.Collection} [collection]
  681. */
  682. _prepareCollection: function( collection ) {
  683. if ( this.related ) {
  684. this.related
  685. .unbind( 'relational:add', this.handleAddition )
  686. .unbind( 'relational:remove', this.handleRemoval )
  687. .unbind( 'relational:reset', this.handleReset )
  688. }
  689. if ( !collection || !( collection instanceof Backbone.Collection ) ) {
  690. collection = new this.collectionType( [], this._getCollectionOptions() );
  691. }
  692. collection.model = this.relatedModel;
  693. if ( this.options.collectionKey ) {
  694. var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey;
  695. if ( collection[ key ] && collection[ key ] !== this.instance ) {
  696. if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
  697. console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey );
  698. }
  699. }
  700. else if ( key ) {
  701. collection[ key ] = this.instance;
  702. }
  703. }
  704. collection
  705. .bind( 'relational:add', this.handleAddition )
  706. .bind( 'relational:remove', this.handleRemoval )
  707. .bind( 'relational:reset', this.handleReset );
  708. return collection;
  709. },
  710. findRelated: function( options ) {
  711. if ( this.keyContents ) {
  712. var models = [];
  713. if ( this.keyContents instanceof Backbone.Collection ) {
  714. models = this.keyContents.models;
  715. }
  716. else {
  717. // Handle cases the an API/user supplies just an Object/id instead of an Array
  718. this.keyContents = _.isArray( this.keyContents ) ? this.keyContents : [ this.keyContents ];
  719. // Try to find instances of the appropriate 'relatedModel' in the store
  720. _.each( this.keyContents, function( item ) {
  721. var model = null;
  722. if ( item instanceof this.relatedModel ) {
  723. model = item;
  724. }
  725. else {
  726. model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } );
  727. }
  728. if ( model && !this.related.getByCid( model ) && !this.related.get( model ) ) {
  729. models.push( model );
  730. }
  731. }, this );
  732. }
  733. // Add all found 'models' in on go, so 'add' will only be called once (and thus 'sort', etc.)
  734. if ( models.length ) {
  735. options = this.unsanitizeOptions( options );
  736. this.related.add( models, options );
  737. }
  738. }
  739. },
  740. /**
  741. * If the key is changed, notify old & new reverse relations and initialize the new relation
  742. */
  743. onChange: function( model, attr, options ) {
  744. options = this.sanitizeOptions( options );
  745. this.keyContents = attr;
  746. // Notify old 'related' object of the terminated relation
  747. _.each( this.getReverseRelations(), function( relation ) {
  748. relation.removeRelated( this.instance, options );
  749. }, this );
  750. // Replace 'this.related' by 'attr' if it is a Backbone.Collection
  751. if ( attr instanceof Backbone.Collection ) {
  752. this._prepareCollection( attr );
  753. this.related = attr;
  754. }
  755. // Otherwise, 'attr' should be an array of related object ids.
  756. // Re-use the current 'this.related' if it is a Backbone.Collection, and remove any current entries.
  757. // Otherwise, create a new collection.
  758. else {
  759. var coll;
  760. if ( this.related instanceof Backbone.Collection ) {
  761. coll = this.related;
  762. coll.remove( coll.models );
  763. }
  764. else {
  765. coll = this._prepareCollection();
  766. }
  767. this.setRelated( coll );
  768. this.findRelated( options );
  769. }
  770. // Notify new 'related' object of the new relation
  771. _.each( this.getReverseRelations(), function( relation ) {
  772. relation.addRelated( this.instance, options );
  773. }, this );
  774. var dit = this;
  775. Backbone.Relational.eventQueue.add( function() {
  776. !options.silentChange && dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options );
  777. });
  778. },
  779. tryAddRelated: function( model, options ) {
  780. options = this.sanitizeOptions( options );
  781. if ( !this.related.getByCid( model ) && !this.related.get( model ) ) {
  782. // Check if this new model was specified in 'this.keyContents'
  783. var item = _.any( this.keyContents, function( item ) {
  784. var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
  785. return id && id === model.id;
  786. }, this );
  787. if ( item ) {
  788. this.related.add( model, options );
  789. }
  790. }
  791. },
  792. /**
  793. * When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations.
  794. * (should be 'HasOne', must set 'this.instance' as their related).
  795. */
  796. handleAddition: function( model, coll, options ) {
  797. //console.debug('handleAddition called; args=%o', arguments);
  798. // Make sure the model is in fact a valid model before continuing.
  799. // (it can be invalid as a result of failing validation in Backbone.Collection._prepareModel)
  800. if ( !( model instanceof Backbone.Model ) ) {
  801. return;
  802. }
  803. options = this.sanitizeOptions( options );
  804. _.each( this.getReverseRelations( model ), function( relation ) {
  805. relation.addRelated( this.instance, options );
  806. }, this );
  807. // Only trigger 'add' once the newly added model is initialized (so, has it's relations set up)
  808. var dit = this;
  809. Backbone.Relational.eventQueue.add( function() {
  810. !options.silentChange && dit.instance.trigger( 'add:' + dit.key, model, dit.related, options );
  811. });
  812. },
  813. /**
  814. * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations.
  815. * (should be 'HasOne', which should be nullified)
  816. */
  817. handleRemoval: function( model, coll, options ) {
  818. //console.debug('handleRemoval called; args=%o', arguments);
  819. if ( !( model instanceof Backbone.Model ) ) {
  820. return;
  821. }
  822. options = this.sanitizeOptions( options );
  823. _.each( this.getReverseRelations( model ), function( relation ) {
  824. relation.removeRelated( this.instance, options );
  825. }, this );
  826. var dit = this;
  827. Backbone.Relational.eventQueue.add( function() {
  828. !options.silentChange && dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options );
  829. });
  830. },
  831. handleReset: function( coll, options ) {
  832. options = this.sanitizeOptions( options );
  833. var dit = this;
  834. Backbone.Relational.eventQueue.add( function() {
  835. !options.silentChange && dit.instance.trigger( 'reset:' + dit.key, dit.related, options );
  836. });
  837. },
  838. addRelated: function( model, options ) {
  839. var dit = this;
  840. options = this.unsanitizeOptions( options );
  841. model.queue( function() { // Queued to avoid errors for adding 'model' to the 'this.related' set twice
  842. if ( dit.related && !dit.related.getByCid( model ) && !dit.related.get( model ) ) {
  843. dit.related.add( model, options );
  844. }
  845. });
  846. },
  847. removeRelated: function( model, options ) {
  848. options = this.unsanitizeOptions( options );
  849. if ( this.related.getByCid( model ) || this.related.get( model ) ) {
  850. this.related.remove( model, options );
  851. }
  852. }
  853. });
  854. /**
  855. * A type of Backbone.Model that also maintains relations to other models and collections.
  856. * New events when compared to the original:
  857. * - 'add:<key>' (model, related collection, options)
  858. * - 'remove:<key>' (model, related collection, options)
  859. * - 'update:<key>' (model, related model or collection, options)
  860. */
  861. Backbone.RelationalModel = Backbone.Model.extend({
  862. relations: null, // Relation descriptions on the prototype
  863. _relations: null, // Relation instances
  864. _isInitialized: false,
  865. _deferProcessing: false,
  866. _queue: null,
  867. subModelTypeAttribute: 'type',
  868. subModelTypes: null,
  869. constructor: function( attributes, options ) {
  870. // Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'.
  871. // Defer 'processQueue', so that when 'Relation.createModels' is used we:
  872. // a) Survive 'Backbone.Collection.add'; this takes care we won't error on "can't add model to a set twice"
  873. // (by creating a model from properties, having the model add itself to the collection via one of
  874. // it's relations, then trying to add it to the collection).
  875. // b) Trigger 'HasMany' collection events only after the model is really fully set up.
  876. // Example that triggers both a and b: "p.get('jobs').add( { company: c, person: p } )".
  877. var dit = this;
  878. if ( options && options.collection ) {
  879. this._deferProcessing = true;
  880. var processQueue = function( model ) {
  881. if ( model === dit ) {
  882. dit._deferProcessing = false;
  883. dit.processQueue();
  884. options.collection.unbind( 'relational:add', processQueue );
  885. }
  886. };
  887. options.collection.bind( 'relational:add', processQueue );
  888. // So we do process the queue eventually, regardless of whether this model really gets added to 'options.collection'.
  889. _.defer( function() {
  890. processQueue( dit );
  891. });
  892. }
  893. this._queue = new Backbone.BlockingQueue();
  894. this._queue.block();
  895. Backbone.Relational.eventQueue.block();
  896. Backbone.Model.apply( this, arguments );
  897. // Try to run the global queue holding external events
  898. Backbone.Relational.eventQueue.unblock();
  899. },
  900. /**
  901. * Override 'trigger' to queue 'change' and 'change:*' events
  902. */
  903. trigger: function( eventName ) {
  904. if ( eventName.length > 5 && 'change' === eventName.substr( 0, 6 ) ) {
  905. var dit = this, args = arguments;
  906. Backbone.Relational.eventQueue.add( function() {
  907. Backbone.Model.prototype.trigger.apply( dit, args );
  908. });
  909. }
  910. else {
  911. Backbone.Model.prototype.trigger.apply( this, arguments );
  912. }
  913. return this;
  914. },
  915. /**
  916. * Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
  917. * Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
  918. */
  919. initializeRelations: function() {
  920. this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
  921. this._relations = [];
  922. _.each( this.relations, function( rel ) {
  923. var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type );
  924. if ( type && type.prototype instanceof Backbone.Relation ) {
  925. new type( this, rel ); // Also pushes the new Relation into _relations
  926. }
  927. else {
  928. Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid type!', rel );
  929. }
  930. }, this );
  931. this._isInitialized = true;
  932. this.release();
  933. this.processQueue();
  934. },
  935. /**
  936. * When new values are set, notify this model's relations (also if options.silent is set).
  937. * (Relation.setRelated locks this model before calling 'set' on it to prevent loops)
  938. */
  939. updateRelations: function( options ) {
  940. if ( this._isInitialized && !this.isLocked() ) {
  941. _.each( this._relations, function( rel ) {
  942. // Update from data in `rel.keySource` if set, or `rel.key` otherwise
  943. var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ];
  944. if ( rel.related !== val ) {
  945. this.trigger( 'relational:change:' + rel.key, this, val, options || {} );
  946. }
  947. }, this );
  948. }
  949. },
  950. /**
  951. * Either add to the queue (if we're not initialized yet), or execute right away.
  952. */
  953. queue: function( func ) {
  954. this._queue.add( func );
  955. },
  956. /**
  957. * Process _queue
  958. */
  959. processQueue: function() {
  960. if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) {
  961. this._queue.unblock();
  962. }
  963. },
  964. /**
  965. * Get a specific relation.
  966. * @param key {string} The relation key to look for.
  967. * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'key', or null.
  968. */
  969. getRelation: function( key ) {
  970. return _.detect( this._relations, function( rel ) {
  971. if ( rel.key === key ) {
  972. return true;
  973. }
  974. }, this );
  975. },
  976. /**
  977. * Get all of the created relations.
  978. * @return {Backbone.Relation[]}
  979. */
  980. getRelations: function() {
  981. return this._relations;
  982. },
  983. /**
  984. * Retrieve related objects.
  985. * @param key {string} The relation key to fetch models for.
  986. * @param options {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
  987. * @param update {boolean} Whether to force a fetch from the server (updating existing models).
  988. * @return {jQuery.when[]} An array of request objects
  989. */
  990. fetchRelated: function( key, options, update ) {
  991. options || ( options = {} );
  992. var setUrl,
  993. requests = [],
  994. rel = this.getRelation( key ),
  995. keyContents = rel && rel.keyContents,
  996. toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
  997. var id = Backbone.Relational.store.resolveIdForItem( rel.relatedModel, item );
  998. return id && ( update || !Backbone.Relational.store.find( rel.relatedModel, id ) );
  999. }, this );
  1000. if ( toFetch && toFetch.length ) {
  1001. // Create a model for each entry in 'keyContents' that is to be fetched
  1002. var models = _.map( toFetch, function( item ) {
  1003. var model;
  1004. if ( _.isObject( item ) ) {
  1005. model = rel.relatedModel.build( item );
  1006. }
  1007. else {
  1008. var attrs = {};
  1009. attrs[ rel.relatedModel.prototype.idAttribute ] = item;
  1010. model = rel.relatedModel.build( attrs );
  1011. }
  1012. return model;
  1013. }, this );
  1014. // Try if the 'collection' can provide a url to fetch a set of models in one request.
  1015. if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
  1016. setUrl = rel.related.url( models );
  1017. }
  1018. // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
  1019. // To make sure it can, test if the url we got by supplying a list of models to fetch is different from
  1020. // the one supplied for the default fetch action (without args to 'url').
  1021. if ( setUrl && setUrl !== rel.related.url() ) {
  1022. var opts = _.defaults(
  1023. {
  1024. error: function() {
  1025. var args = arguments;
  1026. _.each( models, function( model ) {
  1027. model.trigger( 'destroy', model, model.collection, options );
  1028. options.error && options.error.apply( model, args );
  1029. });
  1030. },
  1031. url: setUrl
  1032. },
  1033. options,
  1034. { add: true }
  1035. );
  1036. requests = [ rel.related.fetch( opts ) ];
  1037. }
  1038. else {
  1039. requests = _.map( models, function( model ) {
  1040. var opts = _.defaults(
  1041. {
  1042. error: function() {
  1043. model.trigger( 'destroy', model, model.collection, options );
  1044. options.error && options.error.apply( model, arguments );
  1045. }
  1046. },
  1047. options
  1048. );
  1049. return model.fetch( opts );
  1050. }, this );
  1051. }
  1052. }
  1053. return requests;
  1054. },
  1055. set: function( key, value, options ) {
  1056. Backbone.Relational.eventQueue.block();
  1057. // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object
  1058. var attributes;
  1059. if ( _.isObject( key ) || key == null ) {
  1060. attributes = key;
  1061. options = value;
  1062. }
  1063. else {
  1064. attributes = {};
  1065. attributes[ key ] = value;
  1066. }
  1067. var result = Backbone.Model.prototype.set.apply( this, arguments );
  1068. // Ideal place to set up relations :)
  1069. if ( !this._isInitialized && !this.isLocked() ) {
  1070. this.constructor.initializeModelHierarchy();
  1071. Backbone.Relational.store.register( this );
  1072. this.initializeRelations();
  1073. }
  1074. // Update the 'idAttribute' in Backbone.store if; we don't want it to miss an 'id' update due to {silent:true}
  1075. else if ( attributes && this.idAttribute in attributes ) {
  1076. Backbone.Relational.store.update( this );
  1077. }
  1078. if ( attributes ) {
  1079. this.updateRelations( options );
  1080. }
  1081. // Try to run the global queue holding external events
  1082. Backbone.Relational.eventQueue.unblock();
  1083. return result;
  1084. },
  1085. unset: function( attribute, options ) {
  1086. Backbone.Relational.eventQueue.block();
  1087. var result = Backbone.Model.prototype.unset.apply( this, arguments );
  1088. this.updateRelations( options );
  1089. // Try to run the global queue holding external events
  1090. Backbone.Relational.eventQueue.unblock();
  1091. return result;
  1092. },
  1093. clear: function( options ) {
  1094. Backbone.Relational.eventQueue.block();
  1095. var result = Backbone.Model.prototype.clear.apply( this, arguments );
  1096. this.updateRelations( options );
  1097. // Try to run the global queue holding external events
  1098. Backbone.Relational.eventQueue.unblock();
  1099. return result;
  1100. },
  1101. /**
  1102. * Override 'change', so the change will only execute after 'set' has finised (relations are updated),
  1103. * and 'previousAttributes' will be available when the event is fired.
  1104. */
  1105. change: function( options ) {
  1106. var dit = this, args = arguments;
  1107. Backbone.Relational.eventQueue.add( function() {
  1108. Backbone.Model.prototype.change.apply( dit, args );
  1109. });
  1110. },
  1111. clone: function() {
  1112. var attributes = _.clone( this.attributes );
  1113. if ( !_.isUndefined( attributes[ this.idAttribute ] ) ) {
  1114. attributes[ this.idAttribute ] = null;
  1115. }
  1116. _.each( this.getRelations(), function( rel ) {
  1117. delete attributes[ rel.key ];
  1118. });
  1119. return new this.constructor( attributes );
  1120. },
  1121. /**
  1122. * Convert relations to JSON, omits them when required
  1123. */
  1124. toJSON: function() {
  1125. // If this Model has already been fully serialized in this branch once, return to avoid loops
  1126. if ( this.isLocked() ) {
  1127. return this.id;
  1128. }
  1129. this.acquire();
  1130. var json = Backbone.Model.prototype.toJSON.call( this );
  1131. if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) {
  1132. json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue;
  1133. }
  1134. _.each( this._relations, function( rel ) {
  1135. var value = json[ rel.key ];
  1136. if ( rel.options.includeInJSON === true) {
  1137. if ( value && _.isFunction( value.toJSON ) ) {
  1138. json[ rel.keyDestination ] = value.toJSON();
  1139. }
  1140. else {
  1141. json[ rel.keyDestination ] = null;
  1142. }
  1143. }
  1144. else if ( _.isString( rel.options.includeInJSON ) ) {
  1145. if ( value instanceof Backbone.Collection ) {
  1146. json[ rel.keyDestination ] = value.pluck( rel.options.includeInJSON );
  1147. }
  1148. else if ( value instanceof Backbone.Model ) {
  1149. json[ rel.keyDestination ] = value.get( rel.options.includeInJSON );
  1150. }
  1151. else {
  1152. json[ rel.keyDestination ] = null;
  1153. }
  1154. }
  1155. else if ( _.isArray( rel.options.includeInJSON ) ) {
  1156. if ( value instanceof Backbone.Collection ) {
  1157. var valueSub = [];
  1158. value.each( function( model ) {
  1159. var curJson = {};
  1160. _.each( rel.options.includeInJSON, function( key ) {
  1161. curJson[ key ] = model.get( key );
  1162. });
  1163. valueSub.push( curJson );
  1164. });
  1165. json[ rel.keyDestination ] = valueSub;
  1166. }
  1167. else if ( value instanceof Backbone.Model ) {
  1168. var valueSub = {};
  1169. _.each( rel.options.includeInJSON, function( key ) {
  1170. valueSub[ key ] = value.get( key );
  1171. });
  1172. json[ rel.keyDestination ] = valueSub;
  1173. }
  1174. else {
  1175. json[ rel.keyDestination ] = null;
  1176. }
  1177. }
  1178. else {
  1179. delete json[ rel.key ];
  1180. }
  1181. if ( rel.keyDestination !== rel.key ) {
  1182. delete json[ rel.key ];
  1183. }
  1184. });
  1185. this.release();
  1186. return json;
  1187. }
  1188. },
  1189. {
  1190. setup: function( superModel ) {
  1191. // We don't want to share a relations array with a parent, as this will cause problems with
  1192. // reverse relations.
  1193. this.prototype.relations = ( this.prototype.relations || [] ).slice( 0 );
  1194. this._subModels = {};
  1195. this._superModel = null;
  1196. // If this model has 'subModelTypes' itself, remember them in the store
  1197. if ( this.prototype.hasOwnProperty( 'subModelTypes' ) ) {
  1198. Backbone.Relational.store.addSubModels( this.prototype.subModelTypes, this );
  1199. }
  1200. // The 'subModelTypes' property should not be inherited, so reset it.
  1201. else {
  1202. this.prototype.subModelTypes = null;
  1203. }
  1204. // Initialize all reverseRelations that belong to this new model.
  1205. _.each( this.prototype.relations, function( rel ) {
  1206. if ( !rel.model ) {
  1207. rel.model = this;
  1208. }
  1209. if ( rel.reverseRelation && rel.model === this ) {
  1210. var preInitialize = true;
  1211. if ( _.isString( rel.relatedModel ) ) {
  1212. /**
  1213. * The related model might not be defined for two reasons
  1214. * 1. it never gets defined, e.g. a typo
  1215. * 2. it is related to itself
  1216. * In neither of these cases do we need to pre-initialize reverse relations.
  1217. */
  1218. var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel );
  1219. preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel );
  1220. }
  1221. var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type );
  1222. if ( preInitialize && type && type.prototype instanceof Backbone.Relation ) {
  1223. new type( null, rel );
  1224. }
  1225. }
  1226. }, this );
  1227. },
  1228. /**
  1229. * Create a 'Backbone.Model' instance based on 'attributes'.
  1230. * @param {Object} attributes
  1231. * @param {Object} [options]
  1232. * @return {Backbone.Model}
  1233. */
  1234. build: function( attributes, options ) {
  1235. var model = this;
  1236. // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet.
  1237. this.initializeModelHierarchy();
  1238. // Determine what type of (sub)model should be built if applicable.
  1239. // Lookup the proper subModelType in 'this._subModels'.
  1240. if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) {
  1241. var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ];
  1242. var subModelType = this._subModels[ subModelTypeAttribute ];
  1243. if ( subModelType ) {
  1244. model = subModelType;
  1245. }
  1246. }
  1247. return new model( attributes, options );
  1248. },
  1249. initializeModelHierarchy: function() {
  1250. // If we're here for the first time, try to determine if this modelType has a 'superModel'.
  1251. if ( _.isUndefined( this._superModel ) || _.isNull( this._superModel ) ) {
  1252. Backbone.Relational.store.setupSuperModel( this );
  1253. // If a superModel has been found, copy relations from the _superModel if they haven't been
  1254. // inherited automatically (due to a redefinition of 'relations').
  1255. // Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail
  1256. // the isUndefined/isNull check next time.
  1257. if ( this._superModel ) {
  1258. //
  1259. if ( this._superModel.prototype.relations ) {
  1260. var supermodelRelationsExist = _.any( this.prototype.relations, function( rel ) {
  1261. return rel.model && rel.model !== this;
  1262. }, this );
  1263. if ( !supermodelRelationsExist ) {
  1264. this.prototype.relations = this._superModel.prototype.relations.concat( this.prototype.relations );
  1265. }
  1266. }
  1267. }
  1268. else {
  1269. this._superModel = false;
  1270. }
  1271. }
  1272. // 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.
  1273. if ( this.prototype.subModelTypes && _.keys( this.prototype.subModelTypes ).length !== _.keys( this._subModels ).length ) {
  1274. _.each( this.prototype.subModelTypes, function( subModelTypeName ) {
  1275. var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName );
  1276. subModelType && subModelType.initializeModelHierarchy();
  1277. });
  1278. }
  1279. },
  1280. /**
  1281. * Find an instance of `this` type in 'Backbone.Relational.store'.
  1282. * - If `attributes` is a string or a number, `findOrCreate` will just query the `store` and return a model if found.
  1283. * - If `attributes` is an object, the model will be updated with `attributes` if found.
  1284. * Otherwise, a new model is created with `attributes` (unless `options.create` is explicitly set to `false`).
  1285. * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
  1286. * @param {Object} [options]
  1287. * @param {Boolean} [options.create=true]
  1288. * @return {Backbone.RelationalModel}
  1289. */
  1290. findOrCreate: function( attributes, options ) {
  1291. // Try to find an instance of 'this' model type in the store
  1292. var model = Backbone.Relational.store.find( this, attributes );
  1293. // If we found an instance, update it with the data in 'item'; if not, create an instance
  1294. // (unless 'options.create' is false).
  1295. if ( _.isObject( attributes ) ) {
  1296. if ( model ) {
  1297. model.set( attributes, options );
  1298. }
  1299. else if ( !options || ( options && options.create !== false ) ) {
  1300. model = this.build( attributes, options );
  1301. }
  1302. }
  1303. return model;
  1304. }
  1305. });
  1306. _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore );
  1307. /**
  1308. * Override Backbone.Collection._prepareModel, so objects will be built using the correct type
  1309. * if the collection.model has subModels.
  1310. */
  1311. Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel;
  1312. Backbone.Collection.prototype._prepareModel = function ( model, options ) {
  1313. options || (options = {});
  1314. if ( !( model instanceof Backbone.Model ) ) {
  1315. var attrs = model;
  1316. options.collection = this;
  1317. if ( typeof this.model.build !== 'undefined' ) {
  1318. model = this.model.build( attrs, options );
  1319. }
  1320. else {
  1321. model = new this.model( attrs, options );
  1322. }
  1323. if ( !model._validate( model.attributes, options ) ) {
  1324. model = false;
  1325. }
  1326. }
  1327. else if ( !model.collection ) {
  1328. model.collection = this;
  1329. }
  1330. return model;
  1331. }
  1332. /**
  1333. * Override Backbone.Collection.add, so objects fetched from the server multiple times will
  1334. * update the existing Model. Also, trigger 'relational:add'.
  1335. */
  1336. var add = Backbone.Collection.prototype.__add = Backbone.Collection.prototype.add;
  1337. Backbone.Collection.prototype.add = function( models, options ) {
  1338. options || (options = {});
  1339. if ( !_.isArray( models ) ) {
  1340. models = [ models ];
  1341. }
  1342. var modelsToAdd = [];
  1343. //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options );
  1344. _.each( models, function( model ) {
  1345. if ( !( model instanceof Backbone.Model ) ) {
  1346. // Try to find 'model' in Backbone.store. If it already exists, set the new properties on it.
  1347. var existingModel = Backbone.Relational.store.find( this.model, model[ this.model.prototype.idAttribute ] );
  1348. if ( existingModel ) {
  1349. existingModel.set( existingModel.parse ? existingModel.parse( model ) : model, options );
  1350. model = existingModel;
  1351. }
  1352. else {
  1353. model = Backbone.Collection.prototype._prepareModel.call( this, model, options );
  1354. }
  1355. }
  1356. if ( model instanceof Backbone.Model && !this.get( model ) && !this.getByCid( model ) ) {
  1357. modelsToAdd.push( model );
  1358. }
  1359. }, this );
  1360. // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc).
  1361. if ( modelsToAdd.length ) {
  1362. add.call( this, modelsToAdd, options );
  1363. _.each( modelsToAdd, function( model ) {
  1364. this.trigger( 'relational:add', model, this, options );
  1365. }, this );
  1366. }
  1367. return this;
  1368. };
  1369. /**
  1370. * Override 'Backbone.Collection.remove' to trigger 'relational:remove'.
  1371. */
  1372. var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove;
  1373. Backbone.Collection.prototype.remove = function( models, options ) {
  1374. options || (options = {});
  1375. if ( !_.isArray( models ) ) {
  1376. models = [ models ];
  1377. }
  1378. else {
  1379. models = models.slice( 0 );
  1380. }
  1381. //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options );
  1382. _.each( models, function( model ) {
  1383. model = this.getByCid( model ) || this.get( model );
  1384. if ( model instanceof Backbone.Model ) {
  1385. remove.call( this, model, options );
  1386. this.trigger('relational:remove', model, this, options);
  1387. }
  1388. }, this );
  1389. return this;
  1390. };
  1391. /**
  1392. * Override 'Backbone.Collection.reset' to trigger 'relational:reset'.
  1393. */
  1394. var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset;
  1395. Backbone.Collection.prototype.reset = function( models, options ) {
  1396. reset.call( this, models, options );
  1397. this.trigger( 'relational:reset', this, options );
  1398. return this;
  1399. };
  1400. /**
  1401. * Override 'Backbone.Collection.sort' to trigger 'relational:reset'.
  1402. */
  1403. var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort;
  1404. Backbone.Collection.prototype.sort = function( options ) {
  1405. sort.call( this, options );
  1406. this.trigger( 'relational:reset', this, options );
  1407. return this;
  1408. };
  1409. /**
  1410. * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations
  1411. * are ready.
  1412. */
  1413. var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger;
  1414. Backbone.Collection.prototype.trigger = function( eventName ) {
  1415. if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) {
  1416. var dit = this, args = arguments;
  1417. Backbone.Relational.eventQueue.add( function() {
  1418. trigger.apply( dit, args );
  1419. });
  1420. }
  1421. else {
  1422. trigger.apply( this, arguments );
  1423. }
  1424. return this;
  1425. };
  1426. // Override .extend() to automatically call .setup()
  1427. Backbone.RelationalModel.extend = function( protoProps, classProps ) {
  1428. var child = Backbone.Model.extend.apply( this, arguments );
  1429. child.setup( this );
  1430. return child;
  1431. };
  1432. })();