]> git.proxmox.com Git - sencha-touch.git/blob - src/src/data/association/HasOne.js
import Sencha Touch 2.4.2 source
[sencha-touch.git] / src / src / data / association / HasOne.js
1 /**
2 * Represents a one to one association with another model. The owner model is expected to have
3 * a foreign key which references the primary key of the associated model:
4 *
5 * Ext.define('Person', {
6 * extend: 'Ext.data.Model',
7 * config: {
8 * fields: [
9 * { name: 'id', type: 'int' },
10 * { name: 'name', type: 'string' },
11 * { name: 'address_id', type: 'int'}
12 * ],
13 *
14 * // we can use the hasOne shortcut on the model to create a hasOne association
15 * hasOne: {
16 * model: 'Address',
17 * name : 'address'
18 * }
19 * }
20 * });
21 *
22 * Ext.define('Address', {
23 * extend: 'Ext.data.Model',
24 * config: {
25 * fields: [
26 * { name: 'id', type: 'int' },
27 * { name: 'number', type: 'string' },
28 * { name: 'street', type: 'string' },
29 * { name: 'city', type: 'string' },
30 * { name: 'zip', type: 'string' }
31 * ]
32 * }
33 * });
34 *
35 * In the example above we have created models for People and Addresses, and linked them together
36 * by saying that each Person has a single Address. This automatically links each Person to an Address
37 * based on the Persons address_id, and provides new functions on the Person model:
38 *
39 * ## Generated getter function
40 *
41 * The first function that is added to the owner model is a getter function:
42 *
43 * var person = Ext.create('Person', {
44 * id: 100,
45 * address_id: 20,
46 * name: 'John Smith'
47 * });
48 *
49 * person.getAddress(function(address, operation) {
50 * // do something with the address object
51 * alert(address.get('id')); // alerts 20
52 * }, this);
53 *
54 * The getAddress function was created on the Person model when we defined the association. This uses the
55 * Persons configured {@link Ext.data.proxy.Proxy proxy} to load the Address asynchronously, calling the provided
56 * callback when it has loaded.
57 *
58 * The new getAddress function will also accept an object containing success, failure and callback properties
59 * - callback will always be called, success will only be called if the associated model was loaded successfully
60 * and failure will only be called if the associated model could not be loaded:
61 *
62 * person.getAddress({
63 * reload: true, // force a reload if the owner model is already cached
64 * callback: function(address, operation) {}, // a function that will always be called
65 * success : function(address, operation) {}, // a function that will only be called if the load succeeded
66 * failure : function(address, operation) {}, // a function that will only be called if the load did not succeed
67 * scope : this // optionally pass in a scope object to execute the callbacks in
68 * });
69 *
70 * In each case above the callbacks are called with two arguments - the associated model instance and the
71 * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is
72 * useful when the instance could not be loaded.
73 *
74 * Once the getter has been called on the model, it will be cached if the getter is called a second time. To
75 * force the model to reload, specify reload: true in the options object.
76 *
77 * ## Generated setter function
78 *
79 * The second generated function sets the associated model instance - if only a single argument is passed to
80 * the setter then the following two calls are identical:
81 *
82 * // this call...
83 * person.setAddress(10);
84 *
85 * // is equivalent to this call:
86 * person.set('address_id', 10);
87 *
88 * An instance of the owner model can also be passed as a parameter.
89 *
90 * If we pass in a second argument, the model will be automatically saved and the second argument passed to
91 * the owner model's {@link Ext.data.Model#save save} method:
92 *
93 * person.setAddress(10, function(address, operation) {
94 * // the address has been saved
95 * alert(address.get('address_id')); //now alerts 10
96 * });
97 *
98 * //alternative syntax:
99 * person.setAddress(10, {
100 * callback: function(address, operation) {}, // a function that will always be called
101 * success : function(address, operation) {}, // a function that will only be called if the load succeeded
102 * failure : function(address, operation) {}, // a function that will only be called if the load did not succeed
103 * scope : this //optionally pass in a scope object to execute the callbacks in
104 * });
105 *
106 * ## Customization
107 *
108 * Associations reflect on the models they are linking to automatically set up properties such as the
109 * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified:
110 *
111 * Ext.define('Person', {
112 * extend: 'Ext.data.Model',
113 * config: {
114 * fields: [
115 * // ...
116 * ],
117 *
118 * hasOne: {
119 * model : 'Address',
120 * primaryKey: 'unique_id',
121 * foreignKey: 'addr_id'
122 * }
123 * }
124 * });
125 *
126 * Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'address_id')
127 * with our own settings. Usually this will not be needed.
128 *
129 * ###Further Reading
130 * [Sencha Touch Models and Associations](../../../core_concepts/data/models.html)
131 */
132 Ext.define('Ext.data.association.HasOne', {
133 extend: 'Ext.data.association.Association',
134 alternateClassName: 'Ext.data.HasOneAssociation',
135
136 alias: 'association.hasone',
137
138 config: {
139 /**
140 * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated
141 * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a
142 * model called Person would set up a address_id foreign key.
143 *
144 * Ext.define('Person', {
145 * extend: 'Ext.data.Model',
146 * fields: ['id', 'name', 'address_id'], // refers to the id of the address object
147 * hasOne: 'Address'
148 * });
149 *
150 * Ext.define('Address', {
151 * extend: 'Ext.data.Model',
152 * fields: ['id', 'number', 'street', 'city', 'zip'],
153 * belongsTo: 'Person'
154 * });
155 * var Person = new Person({
156 * id: 1,
157 * name: 'John Smith',
158 * address_id: 13
159 * }, 1);
160 * person.getAddress(); // Will make a call to the server asking for address_id 13
161 *
162 */
163 foreignKey: undefined,
164
165 /**
166 * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype.
167 * Defaults to 'get' + the name of the foreign model, e.g. getAddress
168 */
169 getterName: undefined,
170
171 /**
172 * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype.
173 * Defaults to 'set' + the name of the foreign model, e.g. setAddress
174 */
175 setterName: undefined,
176
177 instanceName: undefined
178 },
179
180 applyForeignKey: function(foreignKey) {
181 if (!foreignKey) {
182 var inverse = this.getInverseAssociation();
183 if (inverse) {
184 foreignKey = inverse.getForeignKey();
185 } else {
186 foreignKey = this.getAssociatedName().toLowerCase() + '_id';
187 }
188 }
189 return foreignKey;
190 },
191
192 updateForeignKey: function(foreignKey, oldForeignKey) {
193 var fields = this.getOwnerModel().getFields(),
194 field = fields.get(foreignKey);
195
196 if (!field) {
197 field = new Ext.data.Field({
198 name: foreignKey
199 });
200 fields.add(field);
201 fields.isDirty = true;
202 }
203
204 if (oldForeignKey) {
205 field = fields.get(oldForeignKey);
206 if (field) {
207 fields.remove(field);
208 fields.isDirty = true;
209 }
210 }
211 },
212
213 applyInstanceName: function(instanceName) {
214 if (!instanceName) {
215 instanceName = this.getAssociatedName() + 'HasOneInstance';
216 }
217 return instanceName;
218 },
219
220 applyAssociationKey: function(associationKey) {
221 if (!associationKey) {
222 var associatedName = this.getAssociatedName();
223 associationKey = associatedName[0].toLowerCase() + associatedName.slice(1);
224 }
225 return associationKey;
226 },
227
228 applyGetterName: function(getterName) {
229 if (!getterName) {
230 var associatedName = this.getAssociatedName();
231 getterName = 'get' + associatedName[0].toUpperCase() + associatedName.slice(1);
232 }
233 return getterName;
234 },
235
236 applySetterName: function(setterName) {
237 if (!setterName) {
238 var associatedName = this.getAssociatedName();
239 setterName = 'set' + associatedName[0].toUpperCase() + associatedName.slice(1);
240 }
241 return setterName;
242 },
243
244 updateGetterName: function(getterName, oldGetterName) {
245 var ownerProto = this.getOwnerModel().prototype;
246 if (oldGetterName) {
247 delete ownerProto[oldGetterName];
248 }
249 if (getterName) {
250 ownerProto[getterName] = this.createGetter();
251 }
252 },
253
254 updateSetterName: function(setterName, oldSetterName) {
255 var ownerProto = this.getOwnerModel().prototype;
256 if (oldSetterName) {
257 delete ownerProto[oldSetterName];
258 }
259 if (setterName) {
260 ownerProto[setterName] = this.createSetter();
261 }
262 },
263
264 /**
265 * @private
266 * Returns a setter function to be placed on the owner model's prototype
267 * @return {Function} The setter function
268 */
269 createSetter: function() {
270 var me = this,
271 foreignKey = me.getForeignKey(),
272 instanceName = me.getInstanceName(),
273 associatedModel = me.getAssociatedModel();
274
275 //'this' refers to the Model instance inside this function
276 return function(value, options, scope) {
277 var Model = Ext.data.Model,
278 record;
279
280 if (value && value.isModel) {
281 value = value.getId();
282 }
283
284 this.set(foreignKey, value);
285
286 if (value || value === 0) {
287 record = Model.cache[Model.generateCacheId(associatedModel.modelName, value)];
288 if (record) {
289 this[instanceName] = record;
290 }
291 } else {
292 delete this[instanceName];
293 }
294
295 if (Ext.isFunction(options)) {
296 options = {
297 callback: options,
298 scope: scope || this
299 };
300 }
301
302 if (Ext.isObject(options)) {
303 return this.save(options);
304 }
305
306 return this;
307 };
308 },
309
310 /**
311 * @private
312 * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance
313 * the first time it is loaded so that subsequent calls to the getter always receive the same reference.
314 * @return {Function} The getter function
315 */
316 createGetter: function() {
317 var me = this,
318 associatedModel = me.getAssociatedModel(),
319 foreignKey = me.getForeignKey(),
320 instanceName = me.getInstanceName();
321
322 //'this' refers to the Model instance inside this function
323 return function(options, scope) {
324 options = options || {};
325
326 var model = this,
327 foreignKeyId = model.get(foreignKey),
328 success, instance, args;
329
330 if (options.reload === true || model[instanceName] === undefined) {
331 if (typeof options == 'function') {
332 options = {
333 callback: options,
334 scope: scope || model
335 };
336 }
337
338 // Overwrite the success handler so we can assign the current instance
339 success = options.success;
340 options.success = function(rec){
341 model[instanceName] = rec;
342 if (success) {
343 success.apply(this, arguments);
344 }
345 };
346
347 associatedModel.load(foreignKeyId, options);
348 } else {
349 instance = model[instanceName];
350 args = [instance];
351 scope = scope || model;
352
353 Ext.callback(options, scope, args);
354 Ext.callback(options.success, scope, args);
355 Ext.callback(options.failure, scope, args);
356 Ext.callback(options.callback, scope, args);
357
358 return instance;
359 }
360 };
361 },
362
363 /**
364 * Read associated data
365 * @private
366 * @param {Ext.data.Model} record The record we're writing to
367 * @param {Ext.data.reader.Reader} reader The reader for the associated model
368 * @param {Object} associationData The raw associated data
369 */
370 read: function(record, reader, associationData) {
371 var inverse = this.getInverseAssociation(),
372 newRecord = reader.read([associationData]).getRecords()[0];
373
374 record[this.getSetterName()].call(record, newRecord);
375
376 //if the inverse association was found, set it now on each record we've just created
377 if (inverse) {
378 newRecord[inverse.getInstanceName()] = record;
379 }
380 },
381
382 getInverseAssociation: function() {
383 var ownerName = this.getOwnerModel().modelName;
384
385 return this.getAssociatedModel().associations.findBy(function(assoc) {
386 return assoc.getType().toLowerCase() === 'belongsto' && assoc.getAssociatedModel().modelName === ownerName;
387 });
388 }
389 });