backbone-relational.js 56 KB

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