HasOne.html 13 KB

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