forked from dojo/dojo1-dgrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_StoreMixin.js
352 lines (305 loc) · 11.2 KB
/
_StoreMixin.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
define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "dojo/aspect", "put-selector/put"],
function(kernel, declare, lang, Deferred, listen, aspect, put){
// This module isolates the base logic required by store-aware list/grid
// components, e.g. OnDemandList/Grid and the Pagination extension.
// Noop function, needed for _trackError when callback due to a bug in 1.8
// (see http://bugs.dojotoolkit.org/ticket/16667)
function noop(value){ return value; }
function emitError(err){
// called by _trackError in context of list/grid, if an error is encountered
if(typeof err !== "object"){
// Ensure we actually have an error object, so we can attach a reference.
err = new Error(err);
}else if(err.dojoType === "cancel"){
// Don't fire dgrid-error events for errors due to canceled requests
// (unfortunately, the Deferred instrumentation will still log them)
return;
}
// TODO: remove this @ 0.4 (prefer grid property directly on event object)
err.grid = this;
if(listen.emit(this.domNode, "dgrid-error", {
grid: this,
error: err,
cancelable: true,
bubbles: true })){
console.error(err);
}
}
return declare(null, {
// store: Object
// The object store (implementing the dojo/store API) from which data is
// to be fetched.
store: null,
// query: Object
// Specifies query parameter(s) to pass to store.query calls.
query: null,
// queryOptions: Object
// Specifies additional query options to mix in when calling store.query;
// sort, start, and count are already handled.
queryOptions: null,
// getBeforePut: boolean
// If true, a get request will be performed to the store before each put
// as a baseline when saving; otherwise, existing row data will be used.
getBeforePut: true,
// noDataMessage: String
// Message to be displayed when no results exist for a query, whether at
// the time of the initial query or upon subsequent observed changes.
// Defined by _StoreMixin, but to be implemented by subclasses.
noDataMessage: "",
// loadingMessage: String
// Message displayed when data is loading.
// Defined by _StoreMixin, but to be implemented by subclasses.
loadingMessage: "",
constructor: function(){
// Create empty objects on each instance, not the prototype
this.query = {};
this.queryOptions = {};
this.dirty = {};
this._updating = {}; // Tracks rows that are mid-update
this._columnsWithSet = {};
// Reset _columnsWithSet whenever column configuration is reset
aspect.before(this, "configStructure", lang.hitch(this, function(){
this._columnsWithSet = {};
}));
},
postCreate: function(){
this.inherited(arguments);
if(this.store){
this._updateNotifyHandle(this.store);
}
},
destroy: function(){
this.inherited(arguments);
if(this._notifyHandle){
this._notifyHandle.remove();
}
},
_configColumn: function(column){
// summary:
// Implements extension point provided by Grid to store references to
// any columns with `set` methods, for use during `save`.
if (column.set){
this._columnsWithSet[column.field] = column;
}
this.inherited(arguments);
},
_updateNotifyHandle: function(store){
// summary:
// Unhooks any previously-existing store.notify handle, and
// hooks up a new one for the given store.
if(this._notifyHandle){
// Unhook notify handler from previous store
this._notifyHandle.remove();
delete this._notifyHandle;
}
if(store && typeof store.notify === "function"){
this._notifyHandle = aspect.after(store, "notify",
lang.hitch(this, "_onNotify"), true);
}
},
_setStore: function(store, query, queryOptions){
// summary:
// Assigns a new store (and optionally query/queryOptions) to the list,
// and tells it to refresh.
this._updateNotifyHandle(store);
this.store = store;
this.dirty = {}; // discard dirty map, as it applied to a previous store
this.set("query", query, queryOptions);
},
_setQuery: function(query, queryOptions){
// summary:
// Assigns a new query (and optionally queryOptions) to the list,
// and tells it to refresh.
var sort = queryOptions && queryOptions.sort;
this.query = query !== undefined ? query : this.query;
this.queryOptions = queryOptions || this.queryOptions;
// If we have new sort criteria, pass them through sort
// (which will update _sort and call refresh in itself).
// Otherwise, just refresh.
sort ? this.set("sort", sort) : this.refresh();
},
setStore: function(store, query, queryOptions){
kernel.deprecated("setStore(...)", 'use set("store", ...) instead', "dgrid 0.4");
this.set("store", store, query, queryOptions);
},
setQuery: function(query, queryOptions){
kernel.deprecated("setQuery(...)", 'use set("query", ...) instead', "dgrid 0.4");
this.set("query", query, queryOptions);
},
_getQueryOptions: function(){
// summary:
// Get a fresh queryOptions object, also including the current sort
var options = lang.delegate(this.queryOptions, {});
if(typeof(this._sort) === "function" || this._sort.length){
// Prevents SimpleQueryEngine from doing unnecessary "null" sorts (which can
// change the ordering in browsers that don't use a stable sort algorithm, eg Chrome)
options.sort = this._sort;
}
return options;
},
_getQuery: function(){
// summary:
// Implemented consistent with _getQueryOptions so that if query is
// an object, this returns a protected (delegated) object instead of
// the original.
var q = this.query;
return typeof q == "object" && q != null ? lang.delegate(q, {}) : q;
},
_setSort: function(property, descending){
// summary:
// Sort the content
// prevent default storeless sort logic as long as we have a store
if(this.store){ this._lastCollection = null; }
this.inherited(arguments);
},
_onNotify: function(object, existingId){
// summary:
// Method called when the store's notify method is called.
// Call inherited in case anything was mixed in earlier
this.inherited(arguments);
// For adds/puts, check whether any observers are hooked up;
// if not, force a refresh to properly hook one up now that there is data
if(object && this._numObservers < 1){
this.refresh({ keepScrollPosition: true });
}
},
insertRow: function(object, parent, beforeNode, i, options){
var store = this.store,
dirty = this.dirty,
id = store && store.getIdentity(object),
dirtyObj;
if(id in dirty && !(id in this._updating)){ dirtyObj = dirty[id]; }
if(dirtyObj){
// restore dirty object as delegate on top of original object,
// to provide protection for subsequent changes as well
object = lang.delegate(object, dirtyObj);
}
return this.inherited(arguments);
},
updateDirty: function(id, field, value){
// summary:
// Updates dirty data of a field for the item with the specified ID.
var dirty = this.dirty,
dirtyObj = dirty[id];
if(!dirtyObj){
dirtyObj = dirty[id] = {};
}
dirtyObj[field] = value;
},
setDirty: function(id, field, value){
kernel.deprecated("setDirty(...)", "use updateDirty() instead", "dgrid 0.4");
this.updateDirty(id, field, value);
},
save: function() {
// Keep track of the store and puts
var self = this,
store = this.store,
dirty = this.dirty,
dfd = new Deferred(), promise = dfd.promise,
getFunc = function(id){
// returns a function to pass as a step in the promise chain,
// with the id variable closured
var data;
return (self.getBeforePut || !(data = self.row(id).data)) ?
function(){ return store.get(id); } :
function(){ return data; };
};
// function called within loop to generate a function for putting an item
function putter(id, dirtyObj) {
// Return a function handler
return function(object) {
var colsWithSet = self._columnsWithSet,
updating = self._updating,
key, data;
if (typeof object.set === "function") {
object.set(dirtyObj);
} else {
// Copy dirty props to the original, applying setters if applicable
for(key in dirtyObj){
object[key] = dirtyObj[key];
}
}
// Apply any set methods in column definitions.
// Note that while in the most common cases column.set is intended
// to return transformed data for the key in question, it is also
// possible to directly modify the object to be saved.
for(key in colsWithSet){
data = colsWithSet[key].set(object);
if(data !== undefined){ object[key] = data; }
}
updating[id] = true;
// Put it in the store, returning the result/promise
return Deferred.when(store.put(object), function() {
// Clear the item now that it's been confirmed updated
delete dirty[id];
delete updating[id];
});
};
}
// For every dirty item, grab the ID
for(var id in dirty) {
// Create put function to handle the saving of the the item
var put = putter(id, dirty[id]);
// Add this item onto the promise chain,
// getting the item from the store first if desired.
promise = promise.then(getFunc(id)).then(put);
}
// Kick off and return the promise representing all applicable get/put ops.
// If the success callback is fired, all operations succeeded; otherwise,
// save will stop at the first error it encounters.
dfd.resolve();
return promise;
},
revert: function(){
// summary:
// Reverts any changes since the previous save.
this.dirty = {};
this.refresh();
},
_trackError: function(func){
// summary:
// Utility function to handle emitting of error events.
// func: Function|String
// A function which performs some store operation, or a String identifying
// a function to be invoked (sans arguments) hitched against the instance.
// If sync, it can return a value, but may throw an error on failure.
// If async, it should return a promise, which would fire the error
// callback on failure.
// tags:
// protected
var result;
if(typeof func == "string"){ func = lang.hitch(this, func); }
try{
result = func();
}catch(err){
// report sync error
emitError.call(this, err);
}
// wrap in when call to handle reporting of potential async error
return Deferred.when(result, noop, lang.hitch(this, emitError));
},
newRow: function(){
// Override to remove no data message when a new row appears.
// Run inherited logic first to prevent confusion due to noDataNode
// no longer being present as a sibling.
var row = this.inherited(arguments);
if(this.noDataNode){
put(this.noDataNode, "!");
delete this.noDataNode;
}
return row;
},
removeRow: function(rowElement, justCleanup){
var row = {element: rowElement};
// Check to see if we are now empty...
if(!justCleanup && this.noDataMessage &&
(this.up(row).element === rowElement) &&
(this.down(row).element === rowElement)){
// ...we are empty, so show the no data message.
this.noDataNode = put(this.contentNode, "div.dgrid-no-data");
this.noDataNode.innerHTML = this.noDataMessage;
}
return this.inherited(arguments);
}
});
});