PageRenderTime 117ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/js/lib/backbone-relational.js

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