/ext-4.1.0_b3/src/data/association/HasOne.js
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 */
116Ext.define('Ext.data.association.HasOne', {
117 extend: 'Ext.data.association.Association',
118 alternateClassName: 'Ext.data.HasOneAssociation',
119
120 alias: 'association.hasone',
121
122 /**
123 * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated
124 * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a
125 * model called Person would set up a address_id foreign key.
126 *
127 * Ext.define('Person', {
128 * extend: 'Ext.data.Model',
129 * fields: ['id', 'name', 'address_id'], // refers to the id of the address object
130 * hasOne: 'Address'
131 * });
132 *
133 * Ext.define('Address', {
134 * extend: 'Ext.data.Model',
135 * fields: ['id', 'number', 'street', 'city', 'zip'],
136 * belongsTo: 'Person'
137 * });
138 * var Person = new Person({
139 * id: 1,
140 * name: 'John Smith',
141 * address_id: 13
142 * }, 1);
143 * person.getAddress(); // Will make a call to the server asking for address_id 13
144 *
145 */
146
147 /**
148 * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype.
149 * Defaults to 'get' + the name of the foreign model, e.g. getAddress
150 */
151
152 /**
153 * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype.
154 * Defaults to 'set' + the name of the foreign model, e.g. setAddress
155 */
156
157 /**
158 * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
159 * Use 'hasOne' to create a HasOne association.
160 *
161 * associations: [{
162 * type: 'hasOne',
163 * model: 'Address'
164 * }]
165 */
166
167 constructor: function(config) {
168 this.callParent(arguments);
169
170 var me = this,
171 ownerProto = me.ownerModel.prototype,
172 associatedName = me.associatedName,
173 getterName = me.getterName || 'get' + associatedName,
174 setterName = me.setterName || 'set' + associatedName;
175
176 Ext.applyIf(me, {
177 name : associatedName,
178 foreignKey : associatedName.toLowerCase() + "_id",
179 instanceName: associatedName + 'HasOneInstance',
180 associationKey: associatedName.toLowerCase()
181 });
182
183 ownerProto[getterName] = me.createGetter();
184 ownerProto[setterName] = me.createSetter();
185 },
186
187 /**
188 * @private
189 * Returns a setter function to be placed on the owner model's prototype
190 * @return {Function} The setter function
191 */
192 createSetter: function() {
193 var me = this,
194 ownerModel = me.ownerModel,
195 foreignKey = me.foreignKey;
196
197 //'this' refers to the Model instance inside this function
198 return function(value, options, scope) {
199 if (value && value.isModel) {
200 value = value.getId();
201 }
202
203 this.set(foreignKey, value);
204
205 if (Ext.isFunction(options)) {
206 options = {
207 callback: options,
208 scope: scope || this
209 };
210 }
211
212 if (Ext.isObject(options)) {
213 return this.save(options);
214 }
215 };
216 },
217
218 /**
219 * @private
220 * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance
221 * the first time it is loaded so that subsequent calls to the getter always receive the same reference.
222 * @return {Function} The getter function
223 */
224 createGetter: function() {
225 var me = this,
226 ownerModel = me.ownerModel,
227 associatedName = me.associatedName,
228 associatedModel = me.associatedModel,
229 foreignKey = me.foreignKey,
230 primaryKey = me.primaryKey,
231 instanceName = me.instanceName;
232
233 //'this' refers to the Model instance inside this function
234 return function(options, scope) {
235 options = options || {};
236
237 var model = this,
238 foreignKeyId = model.get(foreignKey),
239 success,
240 instance,
241 args;
242
243 if (options.reload === true || model[instanceName] === undefined) {
244 instance = Ext.ModelManager.create({}, associatedName);
245 instance.set(primaryKey, foreignKeyId);
246
247 if (typeof options == 'function') {
248 options = {
249 callback: options,
250 scope: scope || model
251 };
252 }
253
254 // Overwrite the success handler so we can assign the current instance
255 success = options.success;
256 options.success = function(rec){
257 model[instanceName] = rec;
258 if (success) {
259 success.call(this, arguments);
260 }
261 };
262
263 associatedModel.load(foreignKeyId, options);
264 // assign temporarily while we wait for data to return
265 model[instanceName] = instance;
266 return instance;
267 } else {
268 instance = model[instanceName];
269 args = [instance];
270 scope = scope || model;
271
272 //TODO: We're duplicating the callback invokation code that the instance.load() call above
273 //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer
274 //instead of the association layer.
275 Ext.callback(options, scope, args);
276 Ext.callback(options.success, scope, args);
277 Ext.callback(options.failure, scope, args);
278 Ext.callback(options.callback, scope, args);
279
280 return instance;
281 }
282 };
283 },
284
285 /**
286 * Read associated data
287 * @private
288 * @param {Ext.data.Model} record The record we're writing to
289 * @param {Ext.data.reader.Reader} reader The reader for the associated model
290 * @param {Object} associationData The raw associated data
291 */
292 read: function(record, reader, associationData){
293 var inverse = this.associatedModel.prototype.associations.findBy(function(assoc){
294 return assoc.type === 'belongsTo' && assoc.associatedName === record.$className;
295 }), newRecord = reader.read([associationData]).records[0];
296
297 record[this.instanceName] = newRecord;
298
299 //if the inverse association was found, set it now on each record we've just created
300 if (inverse) {
301 newRecord[inverse.instanceName] = record;
302 }
303 }
304});