/
model.js
371 lines (291 loc) · 9.66 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
require("ember-data/system/model/states");
require("ember-data/system/mixins/load_promise");
var LoadPromise = DS.LoadPromise; // system/mixins/load_promise
var get = Ember.get, set = Ember.set, map = Ember.EnumerableUtils.map;
var retrieveFromCurrentState = Ember.computed(function(key, value) {
if (arguments.length > 1) {
throw new Error('Cannot Set: ' + key + ' on: ' + this.toString() );
}
return get(get(this, 'stateManager.currentState'), key);
}).property('stateManager.currentState');
DS.Model = Ember.Object.extend(Ember.Evented, LoadPromise, {
isLoaded: retrieveFromCurrentState,
isReloading: retrieveFromCurrentState,
isDirty: retrieveFromCurrentState,
isSaving: retrieveFromCurrentState,
isDeleted: retrieveFromCurrentState,
isError: retrieveFromCurrentState,
isNew: retrieveFromCurrentState,
isValid: retrieveFromCurrentState,
clientId: null,
id: null,
transaction: null,
stateManager: null,
errors: null,
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
Available options:
* `includeId`: `true` if the record's ID should be included in the
JSON representation.
@param {Object} options
@returns {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = get(this, 'store');
return store.serialize(this, options);
},
toJSON: function() {
var serializer = DS.JSONSerializer.create();
return serializer.serialize(this);
},
didLoad: Ember.K,
didReload: Ember.K,
didUpdate: Ember.K,
didCreate: Ember.K,
didDelete: Ember.K,
becameInvalid: Ember.K,
becameError: Ember.K,
data: Ember.computed(function() {
if (!this._data) {
this.materializeData();
}
return this._data;
}).property(),
materializeData: function() {
this.send('materializingData');
get(this, 'store').materializeData(this);
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
_data: null,
init: function() {
this._super();
var stateManager = DS.StateManager.create({ record: this });
set(this, 'stateManager', stateManager);
this._setup();
stateManager.goToState('empty');
},
_setup: function() {
this._relationshipChanges = {};
this._changesToSync = {};
},
send: function(name, context) {
return get(this, 'stateManager').send(name, context);
},
withTransaction: function(fn) {
var transaction = get(this, 'transaction');
if (transaction) { fn(transaction); }
},
loadingData: function() {
this.send('loadingData');
},
loadedData: function() {
this.send('loadedData');
},
didChangeData: function() {
this.send('didChangeData');
},
setProperty: function(key, value, oldValue) {
this.send('setProperty', { key: key, value: value, oldValue: oldValue });
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
*/
reload: function() {
this.send('reloadRecord');
},
deleteRecord: function() {
this.send('deleteRecord');
},
unloadRecord: function() {
Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty'));
this.send('unloadRecord');
},
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
set(this, name, null);
} else if (relationship.kind === 'hasMany') {
get(this, name).clear();
}
}, this);
},
updateRecordArrays: function() {
var store = get(this, 'store');
if (store) {
store.dataWasUpdated(this.constructor, get(this, '_reference'), this);
}
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
*/
adapterDidCommit: function() {
var attributes = get(this, 'data').attributes;
get(this.constructor, 'attributes').forEach(function(name, meta) {
attributes[name] = get(this, name);
}, this);
this.send('didCommit');
this.updateRecordArraysLater();
},
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
dataDidChange: Ember.observer(function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (relationship.kind === 'hasMany') {
this.hasManyDidChange(relationship.key);
}
}, this);
this.send('finishedMaterializing');
}, 'data'),
hasManyDidChange: function(key) {
var cachedValue = this.cacheFor(key);
if (cachedValue) {
var type = get(this.constructor, 'relationshipsByName').get(key).type;
var store = get(this, 'store');
var ids = this._data.hasMany[key] || [];
var references = map(ids, function(id) {
// if it was already a reference, return the reference
if (typeof id === 'object') { return id; }
return store.referenceForId(type, id);
});
set(cachedValue, 'content', Ember.A(references));
}
},
updateRecordArraysLater: function() {
Ember.run.once(this, this.updateRecordArrays);
},
setupData: function(prematerialized) {
this._data = {
attributes: {},
belongsTo: {},
hasMany: {},
id: null
};
},
materializeId: function(id) {
set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes);
this._data.attributes = attributes;
},
materializeAttribute: function(name, value) {
this._data.attributes[name] = value;
},
materializeHasMany: function(name, ids) {
this._data.hasMany[name] = ids;
},
materializeBelongsTo: function(name, id) {
this._data.belongsTo[name] = id;
},
rollback: function() {
this._setup();
this.send('becameClean');
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
toStringExtension: function() {
return get(this, 'id');
},
/**
@private
The goal of this method is to temporarily disable specific observers
that take action in response to application changes.
This allows the system to make changes (such as materialization and
rollback) that should not trigger secondary behavior (such as setting an
inverse relationship or marking records as dirty).
The specific implementation will likely change as Ember proper provides
better infrastructure for suspending groups of observers, and if Array
observation becomes more unified with regular observers.
*/
suspendRelationshipObservers: function(callback, binding) {
var observers = get(this.constructor, 'relationshipNames').belongsTo;
var self = this;
try {
this._suspendedRelationships = true;
Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() {
Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() {
callback.call(binding || self);
});
});
} finally {
this._suspendedRelationships = false;
}
},
becameInFlight: function() {
},
// FOR USE BY THE BASIC ADAPTER
save: function() {
this.get('store').scheduleSave(this);
},
// FOR USE DURING COMMIT PROCESS
adapterDidUpdateAttribute: function(attributeName, value) {
// If a value is passed in, update the internal attributes and clear
// the attribute cache so it picks up the new value. Otherwise,
// collapse the current value into the internal attributes because
// the adapter has acknowledged it.
if (value !== undefined) {
get(this, 'data.attributes')[attributeName] = value;
this.notifyPropertyChange(attributeName);
} else {
value = get(this, attributeName);
get(this, 'data.attributes')[attributeName] = value;
}
this.updateRecordArraysLater();
},
_reference: Ember.computed(function() {
return get(this, 'store').referenceForClientId(get(this, 'clientId'));
}),
adapterDidInvalidate: function(errors) {
this.send('becameInvalid', errors);
},
adapterDidError: function() {
this.send('becameError');
},
/**
@private
Override the default event firing from Ember.Evented to
also call methods with the given name.
*/
trigger: function(name) {
Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
this._super.apply(this, arguments);
}
});
// Helper function to generate store aliases.
// This returns a function that invokes the named alias
// on the default store, but injects the class as the
// first parameter.
var storeAlias = function(methodName) {
return function() {
var store = get(DS, 'defaultStore'),
args = [].slice.call(arguments);
args.unshift(this);
Ember.assert("Your application does not have a 'Store' property defined. Attempts to call '" + methodName + "' on model classes will fail. Please provide one as with 'YourAppName.Store = DS.Store.extend()'", !!store);
return store[methodName].apply(store, args);
};
};
DS.Model.reopenClass({
isLoaded: storeAlias('recordIsLoaded'),
find: storeAlias('find'),
all: storeAlias('all'),
query: storeAlias('findQuery'),
filter: storeAlias('filter'),
_create: DS.Model.create,
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set.");
},
createRecord: storeAlias('createRecord')
});