Debian Codegraph @

dojox/grid/enhanced/plugins/_StoreLayer.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare",
3 "dojo/_base/array",
4 "dojo/_base/lang",
5 "dojo/_base/xhr"
6 ], function(declare, array, lang, xhr){
7 // summary:
8 // The dojo/data/api/Read API is powerful, but it's difficult to give the store some special commands before
9 // fetch, so that the store content can be temporarily modified or transformed, and acts as another store. The
10 // parameter *query* or *queryOptions* in keywordArgs for *fetch* is not enough because:
11 //
12 // 1. users do not have the opportunity to response to the store actions when these options or queries are applied,
13 // especially when the real store is at server side.
14 // 2. the store implementation must be changed to support any new options in 'query' or 'queryOptions', so it'll be
15 // difficult if this implementation is not able to or very hard to be changed, or some new options are required to
16 // be valid for all stores.
17 //
18 // This *StoreLayer* framework is dedicated to provide a uniform way for configuring an existing store, so that
19 // it can be easily extended to have special behaviors or act like a totally different store.
20 // The major approach is to wrap the *fetch* function of store, layer by layer. Every layer treats the incoming
21 // store.fetch as a 'black box', thus maintaining the independence between layers.
22 // *fetch* is the most important data retriever in the Read API, almost all other functions are used for a single
23 // item, and require that this item is already retrieved (by and only by *fetch*). So once we've controlled this
24 // *fetch* function, we've controlled almost the whole store. This fact simplifies our implementation of StoreLayer.
25 // example:
26 // | //ns is for namespace, i.e.:dojox.grid.enhanced.plugins
27 // | ns.wrap(ns.wrap(ns.wrap(store, new ns.FilterLayer()), new ns.UniqueLayer()), new ns.TransformLayer());
28 // |
29 // | //every layer has a name, it should be given in the document of this layer.
30 // | //if you don't know it's name, you can get it by: ns.SomeLayer.prototype.name();
31 // | store.layer("filter").filterDef(...);
32 // | store.layer("unique").setUniqueColumns(...);
33 // | store.layer("transform").setScheme(...);
34 // |
35 // | //now use the store as usual...
36 // |
37 // | store.unwrap("transform"); //remove the transform layer but retain the other two.
38 // |
39 // | //now use the store as usual...
40 // |
41 // | store.unwrap(); //remove all the layers, get the original store back.
42
43 var ns = lang.getObject("grid.enhanced.plugins", true, dojox);
44
45 var getPrevTags = function(tags){
46 var tagList = ["reorder", "sizeChange", "normal", "presentation"];
47 var idx = tagList.length;
48 for(var i = tags.length - 1; i >= 0; --i){
49 var p = array.indexOf(tagList, tags[i]);
50 if(p >= 0 && p <= idx){
51 idx = p;
52 }
53 }
54 if(idx < tagList.length - 1){
55 return tagList.slice(0, idx + 1);
56 }else{
57 return tagList;
58 }
59 },
60
61 unwrap = function(/* string? */layerName){
62 // summary:
63 // Unwrap the layers of the store
64 // tags:
65 // public
66 // returns:
67 // The unwrapped store, for nested use only.
68 var i, layers = this._layers, len = layers.length;
69 if(layerName){
70 for(i = len-1; i >= 0; --i){
71 if(layers[i].name() == layerName){
72 layers[i]._unwrap(layers[i + 1]);
73 break;
74 }
75 }
76 layers.splice(i, 1);
77 }else{
78 for(i = len - 1; i >= 0; --i){
79 layers[i]._unwrap();
80 }
81 }
82 if(!layers.length){
83 delete this._layers;
84 delete this.layer;
85 delete this.unwrap;
86 delete this.forEachLayer;
87 }
88 //console.log("layers:",this._layers);
89 return this; //Read-store
90 },
91
92 getLayer = function(layerName){
93 // summary:
94 // Get a layer of the store, so we can configure that layer.
95 // tags:
96 // public (scope is store)
97 // layerName: string
98 // the name of the layer
99 // returns:
100 // the store layer object
101 var i, layers = this._layers;
102 if(typeof layerName == "undefined"){
103 return layers.length; //Integer
104 }
105 if(typeof layerName == "number"){
106 return layers[layerName]; //_StoreLayer
107 }
108 for(i = layers.length - 1; i >= 0; --i){
109 if(layers[i].name() == layerName){
110 return layers[i]; //_StoreLayer
111 }
112 }
113 return null; //_StoreLayer
114 },
115
116 forEachLayer = function(callback, isInnerToOuter){
117 // summary:
118 // Visit the layers one by one. From the outer most to inner most by default.
119 // callback: Function
120 // The function to callback.
121 // If return false, break the loop.
122 // isInnerToOuter: Boolean
123 // Whether visit from the inner most layer to the outer most layer.
124 var len = this._layers.length, start, end, dir;
125 if(isInnerToOuter){
126 start = 0;
127 end = len;
128 dir = 1;
129 }else{
130 start = len - 1;
131 end = -1;
132 dir = -1;
133 }
134 for(var i = start; i != end; i += dir){
135 if(callback(this._layers[i], i) === false){
136 return i;
137 }
138 }
139 return end;
140 };
141 ns.wrap = function(store, funcName, layer, layerFuncName){
142 // summary:
143 // Wrap the store with the given layer.
144 // tags:
145 // public
146 // store: Read-store
147 // The store to be wrapped.
148 // layer: _StoreLayer
149 // The layer to be used
150 // returns:
151 // The wrapped store, for nested use only.
152 if(!store._layers){
153 store._layers = [];
154 store.layer = lang.hitch(store, getLayer);
155 store.unwrap = lang.hitch(store, unwrap);
156 store.forEachLayer = lang.hitch(store, forEachLayer);
157 }
158 var prevTags = getPrevTags(layer.tags);
159 if(!array.some(store._layers, function(lyr, i){
160 if(array.some(lyr.tags, function(tag){
161 return array.indexOf(prevTags, tag) >= 0;
162 })){
163 return false;
164 }else{
165 store._layers.splice(i, 0, layer);
166 layer._wrap(store, funcName, layerFuncName, lyr);
167 return true;
168 }
169 })){
170 store._layers.push(layer);
171 layer._wrap(store, funcName, layerFuncName);
172 }
173 //console.log("wrapped layers:", dojo.map(store._layers, function(lyr){return lyr.name();}));
174 return store; //Read-store
175 };
176
177 var _StoreLayer = declare("dojox.grid.enhanced.plugins._StoreLayer", null, {
178 // summary:
179 // The most abstract class of store layers, provides basic utilities and some interfaces.
180 // tags:
181 // abstract
182 /*=====
183 // _store: [protected] Read-store
184 // The wrapped store.
185 _store: null,
186
187 // _originFetch: [protected] function
188 // The original fetch function of the store.
189 _originFetch: null,
190
191 // __enabled: [private] Boolean
192 // To control whether this layer is valid.
193 __enabled: true,
194 =====*/
195 tags: ["normal"],
196
197 layerFuncName: "_fetch",
198
199 constructor: function(){
200 this._store = null;
201 this._originFetch = null;
202 this.__enabled = true;
203 },
204 initialize: function(store){
205 },
206 uninitialize: function(store){
207 },
208 invalidate: function(){
209
210 },
211 _wrap: function(store, funcName, layerFuncName, nextLayer){
212 // summary:
213 // Do the actual wrapping (or 'hacking' if you like) to the store.
214 // tags:
215 // internal
216 // store: Read-store
217 // The store to be wrapped.
218 this._store = store;
219 this._funcName = funcName;
220 var fetchFunc = lang.hitch(this, function(){
221 return (this.enabled() ? this[layerFuncName || this.layerFuncName] : this.originFetch).apply(this, arguments);
222 });
223 if(nextLayer){
224 this._originFetch = nextLayer._originFetch;
225 nextLayer._originFetch = fetchFunc;
226 }else{
227 this._originFetch = store[funcName] || function(){};
228 store[funcName] = fetchFunc;
229 }
230 this.initialize(store);
231 },
232 _unwrap: function(nextLayer){
233 // summary:
234 // Do the actual unwrapping to the store.
235 // tags:
236 // internal
237 // store: Read-store
238 // The store to be unwrapped.
239 this.uninitialize(this._store);
240 if(nextLayer){
241 nextLayer._originFetch = this._originFetch;
242 }else{
243 this._store[this._funcName] = this._originFetch;
244 }
245 this._originFetch = null;
246 this._store = null;
247 },
248 enabled: function(/* bool? */toEnable){
249 // summary:
250 // The get/set function of the enabled status of this layer
251 // tags:
252 // public
253 // toEnable: Boolean?
254 // If given, is a setter, otherwise, it's getter.
255 if(typeof toEnable != "undefined"){
256 this.__enabled = !!toEnable;
257 }
258 return this.__enabled; //Boolean
259 },
260 name: function(){
261 // summary:
262 // Get the name of this store layer.
263 // The default name retrieved from class name, which should have a pattern of "{name}Layer".
264 // If this pattern does not exist, the whole class name will be this layer's name.
265 // It's better to override this method if your class name is too complicated.
266 // tags:
267 // public extension
268 // returns:
269 // The name of this layer.
270 if(!this.__name){
271 var m = this.declaredClass.match(/(?:\.(?:_*)([^\.]+)Layer$)|(?:\.([^\.]+)$)/i);
272 this.__name = m ? (m[1] || m[2]).toLowerCase() : this.declaredClass;
273 }
274 return this.__name;
275 },
276 originFetch: function(){
277 return (lang.hitch(this._store, this._originFetch)).apply(this, arguments);
278 }
279 });
280 var _ServerSideLayer = declare("dojox.grid.enhanced.plugins._ServerSideLayer", _StoreLayer, {
281 // summary:
282 // The most abstract class for all server side store layers.
283 // tags:
284 // abstract
285 /*=====
286 // _url: [protected] string
287 // The url of the server
288 _url: "",
289 // __cmds [private] object
290 // The command object to be sent to server.
291 __cmds: {},
292 =====*/
293 constructor: function(args){
294 args = args || {};
295 this._url = args.url || "";
296 this._isStateful = !!args.isStateful;
297 this._onUserCommandLoad = args.onCommandLoad || function(){};
298 this.__cmds = {cmdlayer:this.name(), enable:true};
299
300 //Only for stateful server, sending commands before fetch makes sense.
301 this.useCommands(this._isStateful);
302 },
303 enabled: function(/* bool? */toEnable){
304 // summary:
305 // Overrided from _StoreLayer.enabled
306 var res = this.inherited(arguments);
307 this.__cmds.enable = this.__enabled;
308 return res;
309 },
310 useCommands: function(/* bool? */toUse){
311 // summary:
312 // If you only want to modify the user request, instead of sending a separate command
313 // to server before fetch, just call:
314 // | this.useCommand(false);
315 // tags:
316 // public
317 // toUse: Boolean?
318 // If provided, it's a setter, otherwise, it's a getter
319 if(typeof toUse != "undefined"){
320 this.__cmds.cmdlayer = (toUse && this._isStateful) ? this.name() : null;
321 }
322 return !!(this.__cmds.cmdlayer); //Boolean
323 },
324 _fetch: function(/* keywordArgs */userRequest){
325 // summary:
326 // Implementation of _StoreLayer._fetch
327 if(this.__cmds.cmdlayer){
328 //We're gonna send command to server before fetch.
329 xhr.post({
330 url: this._url || this._store.url,
331 content: this.__cmds,
332 load: lang.hitch(this, function(responce){
333 this.onCommandLoad(responce, userRequest);
334 this.originFetch(userRequest);
335 }),
336 error: lang.hitch(this, this.onCommandError)
337 });
338 }else{
339 //The user only wants to modify the request object.
340 this.onCommandLoad("", userRequest);
341 this.originFetch(userRequest);
342 }
343 return userRequest; // dojo/data/api/Request
344 },
345 command: function(/* string */cmdName,/* (string|number|bool|...)? */cmdContent){
346 // summary:
347 // get/set a command (a name-value pair)
348 // tags:
349 // public
350 // cmdName: string
351 // The name of the command
352 // cmdContent: anything
353 // The content of the command
354 // returns:
355 // The content of the command if cmdContent is undefined
356 var cmds = this.__cmds;
357 if(cmdContent === null){
358 delete cmds[cmdName];
359 }else if(typeof cmdContent !== "undefined"){
360 cmds[cmdName] = cmdContent;
361 }
362 return cmds[cmdName]; //anything
363 },
364 onCommandLoad: function(/* string */response, /* keywordArgs */userRequest){
365 // summary:
366 // When the server gives back *response* for the commands, you can do something here.
367 // tags:
368 // callback extension
369 // response: string
370 // server response
371 // userRequest: [in|out] dojo/data/api/Request
372 // The request object for *fetch*. You can modify this object according to the *response*
373 // so as to change the behavior of *fetch*
374 this._onUserCommandLoad(this.__cmds, userRequest, response);
375 },
376 onCommandError: function(error){
377 // summary:
378 // handle errors when sending commands.
379 // tags:
380 // callback extension
381 // error: Error
382 console.log(error);
383 throw error;
384 }
385 });
386
387 return {
388 _StoreLayer: _StoreLayer,
389 _ServerSideLayer: _ServerSideLayer,
390 wrap: ns.wrap
391 };
392 });