PageRenderTime 63ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/backbone-relational/0.7.0/backbone-relational.js

https://bitbucket.org/kolbyjAFK/cdnjs
JavaScript | 1715 lines | 1122 code | 247 blank | 346 comment | 307 complexity | 7f41014b90d7da9cc348046e2e5ba7fc MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file