/ext-4.1.0_b3/src/data/association/HasOne.js

https://bitbucket.org/srogerf/javascript · JavaScript · 304 lines · 96 code · 26 blank · 182 comment · 18 complexity · 3093bd5497a9c441854c30fc2f04da5c MD5 · raw file

  1. /**
  2. * @class Ext.data.association.HasOne
  3. *
  4. * Represents a one to one association with another model. The owner model is expected to have
  5. * a foreign key which references the primary key of the associated model:
  6. *
  7. * Ext.define('Person', {
  8. * extend: 'Ext.data.Model',
  9. * fields: [
  10. * { name: 'id', type: 'int' },
  11. * { name: 'name', type: 'string' },
  12. * { name: 'address_id', type: 'int'}
  13. * ]
  14. * });
  15. *
  16. * Ext.define('Address', {
  17. * extend: 'Ext.data.Model',
  18. * fields: [
  19. * { name: 'id', type: 'int' },
  20. * { name: 'number', type: 'string' },
  21. * { name: 'street', type: 'string' },
  22. * { name: 'city', type: 'string' },
  23. * { name: 'zip', type: 'string' },
  24. * ],
  25. * // we can use the hasOne shortcut on the model to create a hasOne association
  26. * associations: { type: 'hasOne', model: 'Address' }
  27. * });
  28. *
  29. * In the example above we have created models for People and Addresses, and linked them together
  30. * by saying that each Person has a single Address. This automatically links each Person to an Address
  31. * based on the Persons address_id, and provides new functions on the Person model:
  32. *
  33. * ## Generated getter function
  34. *
  35. * The first function that is added to the owner model is a getter function:
  36. *
  37. * var person = new Person({
  38. * id: 100,
  39. * address_id: 20,
  40. * name: 'John Smith'
  41. * });
  42. *
  43. * person.getAddress(function(address, operation) {
  44. * // do something with the address object
  45. * alert(address.get('id')); // alerts 20
  46. * }, this);
  47. *
  48. * The getAddress function was created on the Person model when we defined the association. This uses the
  49. * Persons configured {@link Ext.data.proxy.Proxy proxy} to load the Address asynchronously, calling the provided
  50. * callback when it has loaded.
  51. *
  52. * The new getAddress function will also accept an object containing success, failure and callback properties
  53. * - callback will always be called, success will only be called if the associated model was loaded successfully
  54. * and failure will only be called if the associatied model could not be loaded:
  55. *
  56. * person.getAddress({
  57. * reload: true, // force a reload if the owner model is already cached
  58. * callback: function(address, operation) {}, // a function that will always be called
  59. * success : function(address, operation) {}, // a function that will only be called if the load succeeded
  60. * failure : function(address, operation) {}, // a function that will only be called if the load did not succeed
  61. * scope : this // optionally pass in a scope object to execute the callbacks in
  62. * });
  63. *
  64. * In each case above the callbacks are called with two arguments - the associated model instance and the
  65. * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is
  66. * useful when the instance could not be loaded.
  67. *
  68. * Once the getter has been called on the model, it will be cached if the getter is called a second time. To
  69. * force the model to reload, specify reload: true in the options object.
  70. *
  71. * ## Generated setter function
  72. *
  73. * The second generated function sets the associated model instance - if only a single argument is passed to
  74. * the setter then the following two calls are identical:
  75. *
  76. * // this call...
  77. * person.setAddress(10);
  78. *
  79. * // is equivalent to this call:
  80. * person.set('address_id', 10);
  81. *
  82. * An instance of the owner model can also be passed as a parameter.
  83. *
  84. * If we pass in a second argument, the model will be automatically saved and the second argument passed to
  85. * the owner model's {@link Ext.data.Model#save save} method:
  86. *
  87. * person.setAddress(10, function(address, operation) {
  88. * // the address has been saved
  89. * alert(address.get('address_id')); //now alerts 10
  90. * });
  91. *
  92. * //alternative syntax:
  93. * person.setAddress(10, {
  94. * callback: function(address, operation), // a function that will always be called
  95. * success : function(address, operation), // a function that will only be called if the load succeeded
  96. * failure : function(address, operation), // a function that will only be called if the load did not succeed
  97. * scope : this //optionally pass in a scope object to execute the callbacks in
  98. * })
  99. *
  100. * ## Customisation
  101. *
  102. * Associations reflect on the models they are linking to automatically set up properties such as the
  103. * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified:
  104. *
  105. * Ext.define('Person', {
  106. * fields: [...],
  107. *
  108. * associations: [
  109. * { type: 'hasOne', model: 'Address', primaryKey: 'unique_id', foreignKey: 'addr_id' }
  110. * ]
  111. * });
  112. *
  113. * Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'address_id')
  114. * with our own settings. Usually this will not be needed.
  115. */
  116. Ext.define('Ext.data.association.HasOne', {
  117. extend: 'Ext.data.association.Association',
  118. alternateClassName: 'Ext.data.HasOneAssociation',
  119. alias: 'association.hasone',
  120. /**
  121. * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated
  122. * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a
  123. * model called Person would set up a address_id foreign key.
  124. *
  125. * Ext.define('Person', {
  126. * extend: 'Ext.data.Model',
  127. * fields: ['id', 'name', 'address_id'], // refers to the id of the address object
  128. * hasOne: 'Address'
  129. * });
  130. *
  131. * Ext.define('Address', {
  132. * extend: 'Ext.data.Model',
  133. * fields: ['id', 'number', 'street', 'city', 'zip'],
  134. * belongsTo: 'Person'
  135. * });
  136. * var Person = new Person({
  137. * id: 1,
  138. * name: 'John Smith',
  139. * address_id: 13
  140. * }, 1);
  141. * person.getAddress(); // Will make a call to the server asking for address_id 13
  142. *
  143. */
  144. /**
  145. * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype.
  146. * Defaults to 'get' + the name of the foreign model, e.g. getAddress
  147. */
  148. /**
  149. * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype.
  150. * Defaults to 'set' + the name of the foreign model, e.g. setAddress
  151. */
  152. /**
  153. * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
  154. * Use 'hasOne' to create a HasOne association.
  155. *
  156. * associations: [{
  157. * type: 'hasOne',
  158. * model: 'Address'
  159. * }]
  160. */
  161. constructor: function(config) {
  162. this.callParent(arguments);
  163. var me = this,
  164. ownerProto = me.ownerModel.prototype,
  165. associatedName = me.associatedName,
  166. getterName = me.getterName || 'get' + associatedName,
  167. setterName = me.setterName || 'set' + associatedName;
  168. Ext.applyIf(me, {
  169. name : associatedName,
  170. foreignKey : associatedName.toLowerCase() + "_id",
  171. instanceName: associatedName + 'HasOneInstance',
  172. associationKey: associatedName.toLowerCase()
  173. });
  174. ownerProto[getterName] = me.createGetter();
  175. ownerProto[setterName] = me.createSetter();
  176. },
  177. /**
  178. * @private
  179. * Returns a setter function to be placed on the owner model's prototype
  180. * @return {Function} The setter function
  181. */
  182. createSetter: function() {
  183. var me = this,
  184. ownerModel = me.ownerModel,
  185. foreignKey = me.foreignKey;
  186. //'this' refers to the Model instance inside this function
  187. return function(value, options, scope) {
  188. if (value && value.isModel) {
  189. value = value.getId();
  190. }
  191. this.set(foreignKey, value);
  192. if (Ext.isFunction(options)) {
  193. options = {
  194. callback: options,
  195. scope: scope || this
  196. };
  197. }
  198. if (Ext.isObject(options)) {
  199. return this.save(options);
  200. }
  201. };
  202. },
  203. /**
  204. * @private
  205. * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance
  206. * the first time it is loaded so that subsequent calls to the getter always receive the same reference.
  207. * @return {Function} The getter function
  208. */
  209. createGetter: function() {
  210. var me = this,
  211. ownerModel = me.ownerModel,
  212. associatedName = me.associatedName,
  213. associatedModel = me.associatedModel,
  214. foreignKey = me.foreignKey,
  215. primaryKey = me.primaryKey,
  216. instanceName = me.instanceName;
  217. //'this' refers to the Model instance inside this function
  218. return function(options, scope) {
  219. options = options || {};
  220. var model = this,
  221. foreignKeyId = model.get(foreignKey),
  222. success,
  223. instance,
  224. args;
  225. if (options.reload === true || model[instanceName] === undefined) {
  226. instance = Ext.ModelManager.create({}, associatedName);
  227. instance.set(primaryKey, foreignKeyId);
  228. if (typeof options == 'function') {
  229. options = {
  230. callback: options,
  231. scope: scope || model
  232. };
  233. }
  234. // Overwrite the success handler so we can assign the current instance
  235. success = options.success;
  236. options.success = function(rec){
  237. model[instanceName] = rec;
  238. if (success) {
  239. success.call(this, arguments);
  240. }
  241. };
  242. associatedModel.load(foreignKeyId, options);
  243. // assign temporarily while we wait for data to return
  244. model[instanceName] = instance;
  245. return instance;
  246. } else {
  247. instance = model[instanceName];
  248. args = [instance];
  249. scope = scope || model;
  250. //TODO: We're duplicating the callback invokation code that the instance.load() call above
  251. //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer
  252. //instead of the association layer.
  253. Ext.callback(options, scope, args);
  254. Ext.callback(options.success, scope, args);
  255. Ext.callback(options.failure, scope, args);
  256. Ext.callback(options.callback, scope, args);
  257. return instance;
  258. }
  259. };
  260. },
  261. /**
  262. * Read associated data
  263. * @private
  264. * @param {Ext.data.Model} record The record we're writing to
  265. * @param {Ext.data.reader.Reader} reader The reader for the associated model
  266. * @param {Object} associationData The raw associated data
  267. */
  268. read: function(record, reader, associationData){
  269. var inverse = this.associatedModel.prototype.associations.findBy(function(assoc){
  270. return assoc.type === 'belongsTo' && assoc.associatedName === record.$className;
  271. }), newRecord = reader.read([associationData]).records[0];
  272. record[this.instanceName] = newRecord;
  273. //if the inverse association was found, set it now on each record we've just created
  274. if (inverse) {
  275. newRecord[inverse.instanceName] = record;
  276. }
  277. }
  278. });