Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / pkgs / direct-debug.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.data.DirectProxy\r
9  * @extends Ext.data.DataProxy\r
10  */\r
11 Ext.data.DirectProxy = function(config){\r
12     Ext.apply(this, config);\r
13     if(typeof this.paramOrder == 'string'){\r
14         this.paramOrder = this.paramOrder.split(/[\s,|]/);\r
15     }\r
16     Ext.data.DirectProxy.superclass.constructor.call(this, config);\r
17 };\r
18 \r
19 Ext.extend(Ext.data.DirectProxy, Ext.data.DataProxy, {\r
20     /**\r
21      * @cfg {Array/String} paramOrder Defaults to <tt>undefined</tt>. A list of params to be executed\r
22      * server side.  Specify the params in the order in which they must be executed on the server-side\r
23      * as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,\r
24      * comma, or pipe. For example,\r
25      * any of the following would be acceptable:<pre><code>\r
26 paramOrder: ['param1','param2','param3']\r
27 paramOrder: 'param1 param2 param3'\r
28 paramOrder: 'param1,param2,param3'\r
29 paramOrder: 'param1|param2|param'\r
30      </code></pre>\r
31      */\r
32     paramOrder: undefined,\r
33 \r
34     /**\r
35      * @cfg {Boolean} paramsAsHash\r
36      * Send parameters as a collection of named arguments (defaults to <tt>true</tt>). Providing a\r
37      * <tt>{@link #paramOrder}</tt> nullifies this configuration.\r
38      */\r
39     paramsAsHash: true,\r
40 \r
41     /**\r
42      * @cfg {Function} directFn\r
43      * Function to call when executing a request.  directFn is a simple alternative to defining the api configuration-parameter\r
44      * for Store's which will not implement a full CRUD api.\r
45      */\r
46     directFn : undefined,\r
47 \r
48     // protected\r
49     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
50         var args = [];\r
51         var directFn = this.api[action] || this.directFn;\r
52 \r
53         switch (action) {\r
54             case Ext.data.Api.actions.create:\r
55                 args.push(params[reader.meta.root]);            // <-- create(Hash)\r
56                 break;\r
57             case Ext.data.Api.actions.read:\r
58                 if(this.paramOrder){\r
59                     for(var i = 0, len = this.paramOrder.length; i < len; i++){\r
60                         args.push(params[this.paramOrder[i]]);\r
61                     }\r
62                 }else if(this.paramsAsHash){\r
63                     args.push(params);\r
64                 }\r
65                 break;\r
66             case Ext.data.Api.actions.update:\r
67                 args.push(params[reader.meta.idProperty]);  // <-- save(Integer/Integer[], Hash/Hash[])\r
68                 args.push(params[reader.meta.root]);\r
69                 break;\r
70             case Ext.data.Api.actions.destroy:\r
71                 args.push(params[reader.meta.root]);        // <-- destroy(Int/Int[])\r
72                 break;\r
73         }\r
74 \r
75         var trans = {\r
76             params : params || {},\r
77             callback : callback,\r
78             scope : scope,\r
79             arg : options,\r
80             reader: reader\r
81         };\r
82 \r
83         args.push(this.createCallback(action, rs, trans), this);\r
84         directFn.apply(window, args);\r
85     },\r
86 \r
87     // private\r
88     createCallback : function(action, rs, trans) {\r
89         return function(result, res) {\r
90             if (!res.status) {\r
91                 // @deprecated fire loadexception\r
92                 if (action === Ext.data.Api.actions.read) {\r
93                     this.fireEvent("loadexception", this, trans, res, null);\r
94                 }\r
95                 this.fireEvent('exception', this, 'remote', action, trans, res, null);\r
96                 trans.callback.call(trans.scope, null, trans.arg, false);\r
97                 return;\r
98             }\r
99             if (action === Ext.data.Api.actions.read) {\r
100                 this.onRead(action, trans, result, res);\r
101             } else {\r
102                 this.onWrite(action, trans, result, res, rs);\r
103             }\r
104         };\r
105     },\r
106     /**\r
107      * Callback for read actions\r
108      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
109      * @param {Object} trans The request transaction object\r
110      * @param {Object} res The server response\r
111      * @private\r
112      */\r
113     onRead : function(action, trans, result, res) {\r
114         var records;\r
115         try {\r
116             records = trans.reader.readRecords(result);\r
117         }\r
118         catch (ex) {\r
119             // @deprecated: Fire old loadexception for backwards-compat.\r
120             this.fireEvent("loadexception", this, trans, res, ex);\r
121 \r
122             this.fireEvent('exception', this, 'response', action, trans, res, ex);\r
123             trans.callback.call(trans.scope, null, trans.arg, false);\r
124             return;\r
125         }\r
126         this.fireEvent("load", this, res, trans.arg);\r
127         trans.callback.call(trans.scope, records, trans.arg, true);\r
128     },\r
129     /**\r
130      * Callback for write actions\r
131      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
132      * @param {Object} trans The request transaction object\r
133      * @param {Object} res The server response\r
134      * @private\r
135      */\r
136     onWrite : function(action, trans, result, res, rs) {\r
137         this.fireEvent("write", this, action, result, res, rs, trans.arg);\r
138         trans.callback.call(trans.scope, result, res, true);\r
139     }\r
140 });\r
141 \r
142 /**\r
143  * @class Ext.data.DirectStore\r
144  * @extends Ext.data.Store\r
145  * <p>Small helper class to create an {@link Ext.data.Store} configured with an\r
146  * {@link Ext.data.DirectProxy} and {@link Ext.data.JsonReader} to make interacting\r
147  * with an {@link Ext.Direct} Server-side {@link Ext.direct.Provider Provider} easier.\r
148  * To create a different proxy/reader combination create a basic {@link Ext.data.Store}\r
149  * configured as needed.</p>\r
150  *\r
151  * <p><b>*Note:</b> Although they are not listed, this class inherits all of the config options of:</p>\r
152  * <div><ul class="mdetail-params">\r
153  * <li><b>{@link Ext.data.Store Store}</b></li>\r
154  * <div class="sub-desc"><ul class="mdetail-params">\r
155  *\r
156  * </ul></div>\r
157  * <li><b>{@link Ext.data.JsonReader JsonReader}</b></li>\r
158  * <div class="sub-desc"><ul class="mdetail-params">\r
159  * <li><tt><b>{@link Ext.data.JsonReader#root root}</b></tt></li>\r
160  * <li><tt><b>{@link Ext.data.JsonReader#idProperty idProperty}</b></tt></li>\r
161  * <li><tt><b>{@link Ext.data.JsonReader#totalProperty totalProperty}</b></tt></li>\r
162  * </ul></div>\r
163  *\r
164  * <li><b>{@link Ext.data.DirectProxy DirectProxy}</b></li>\r
165  * <div class="sub-desc"><ul class="mdetail-params">\r
166  * <li><tt><b>{@link Ext.data.DirectProxy#directFn directFn}</b></tt></li>\r
167  * <li><tt><b>{@link Ext.data.DirectProxy#paramOrder paramOrder}</b></tt></li>\r
168  * <li><tt><b>{@link Ext.data.DirectProxy#paramsAsHash paramsAsHash}</b></tt></li>\r
169  * </ul></div>\r
170  * </ul></div>\r
171  *\r
172  * @xtype directstore\r
173  *\r
174  * @constructor\r
175  * @param {Object} config\r
176  */\r
177 Ext.data.DirectStore = function(c){\r
178     // each transaction upon a singe record will generatie a distinct Direct transaction since Direct queues them into one Ajax request.\r
179     c.batchTransactions = false;\r
180 \r
181     Ext.data.DirectStore.superclass.constructor.call(this, Ext.apply(c, {\r
182         proxy: (typeof(c.proxy) == 'undefined') ? new Ext.data.DirectProxy(Ext.copyTo({}, c, 'paramOrder,paramsAsHash,directFn,api')) : c.proxy,\r
183         reader: (typeof(c.reader) == 'undefined' && typeof(c.fields) == 'object') ? new Ext.data.JsonReader(Ext.copyTo({}, c, 'totalProperty,root,idProperty'), c.fields) : c.reader\r
184     }));\r
185 };\r
186 Ext.extend(Ext.data.DirectStore, Ext.data.Store, {});\r
187 Ext.reg('directstore', Ext.data.DirectStore);
188 /**\r
189  * @class Ext.Direct\r
190  * @extends Ext.util.Observable\r
191  * <p><b><u>Overview</u></b></p>\r
192  * \r
193  * <p>Ext.Direct aims to streamline communication between the client and server\r
194  * by providing a single interface that reduces the amount of common code\r
195  * typically required to validate data and handle returned data packets\r
196  * (reading data, error conditions, etc).</p>\r
197  *  \r
198  * <p>The Ext.direct namespace includes several classes for a closer integration\r
199  * with the server-side. The Ext.data namespace also includes classes for working\r
200  * with Ext.data.Stores which are backed by data from an Ext.Direct method.</p>\r
201  * \r
202  * <p><b><u>Specification</u></b></p>\r
203  * \r
204  * <p>For additional information consult the \r
205  * <a href="http://extjs.com/products/extjs/direct.php">Ext.Direct Specification</a>.</p>\r
206  *   \r
207  * <p><b><u>Providers</u></b></p>\r
208  * \r
209  * <p>Ext.Direct uses a provider architecture, where one or more providers are\r
210  * used to transport data to and from the server. There are several providers\r
211  * that exist in the core at the moment:</p><div class="mdetail-params"><ul>\r
212  * \r
213  * <li>{@link Ext.direct.JsonProvider JsonProvider} for simple JSON operations</li>\r
214  * <li>{@link Ext.direct.PollingProvider PollingProvider} for repeated requests</li>\r
215  * <li>{@link Ext.direct.RemotingProvider RemotingProvider} exposes server side\r
216  * on the client.</li>\r
217  * </ul></div>\r
218  * \r
219  * <p>A provider does not need to be invoked directly, providers are added via\r
220  * {@link Ext.Direct}.{@link Ext.Direct#add add}.</p>\r
221  * \r
222  * <p><b><u>Router</u></b></p>\r
223  * \r
224  * <p>Ext.Direct utilizes a "router" on the server to direct requests from the client\r
225  * to the appropriate server-side method. Because the Ext.Direct API is completely\r
226  * platform-agnostic, you could completely swap out a Java based server solution\r
227  * and replace it with one that uses C# without changing the client side JavaScript\r
228  * at all.</p>\r
229  * \r
230  * <p><b><u>Server side events</u></b></p>\r
231  * \r
232  * <p>Custom events from the server may be handled by the client by adding\r
233  * listeners, for example:</p>\r
234  * <pre><code>\r
235 {"type":"event","name":"message","data":"Successfully polled at: 11:19:30 am"}\r
236 \r
237 // add a handler for a 'message' event sent by the server \r
238 Ext.Direct.on('message', function(e){\r
239     out.append(String.format('&lt;p>&lt;i>{0}&lt;/i>&lt;/p>', e.data));\r
240             out.el.scrollTo('t', 100000, true);\r
241 });\r
242  * </code></pre>\r
243  * @singleton\r
244  */\r
245 Ext.Direct = Ext.extend(Ext.util.Observable, {\r
246     /**\r
247      * Each event type implements a getData() method. The default event types are:\r
248      * <div class="mdetail-params"><ul>\r
249      * <li><b><tt>event</tt></b> : Ext.Direct.Event</li>\r
250      * <li><b><tt>exception</tt></b> : Ext.Direct.ExceptionEvent</li>\r
251      * <li><b><tt>rpc</tt></b> : Ext.Direct.RemotingEvent</li>\r
252      * </ul></div>\r
253      * @property eventTypes\r
254      * @type Object\r
255      */\r
256 \r
257     /**\r
258      * Four types of possible exceptions which can occur:\r
259      * <div class="mdetail-params"><ul>\r
260      * <li><b><tt>Ext.Direct.exceptions.TRANSPORT</tt></b> : 'xhr'</li>\r
261      * <li><b><tt>Ext.Direct.exceptions.PARSE</tt></b> : 'parse'</li>\r
262      * <li><b><tt>Ext.Direct.exceptions.LOGIN</tt></b> : 'login'</li>\r
263      * <li><b><tt>Ext.Direct.exceptions.SERVER</tt></b> : 'exception'</li>\r
264      * </ul></div>\r
265      * @property exceptions\r
266      * @type Object\r
267      */\r
268     exceptions: {\r
269         TRANSPORT: 'xhr',\r
270         PARSE: 'parse',\r
271         LOGIN: 'login',\r
272         SERVER: 'exception'\r
273     },\r
274     \r
275     // private\r
276     constructor: function(){\r
277         this.addEvents(\r
278             /**\r
279              * @event event\r
280              * Fires after an event.\r
281              * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.\r
282              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.\r
283              */\r
284             'event',\r
285             /**\r
286              * @event exception\r
287              * Fires after an event exception.\r
288              * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.\r
289              */\r
290             'exception'\r
291         );\r
292         this.transactions = {};\r
293         this.providers = {};\r
294     },\r
295 \r
296     /**\r
297      * Adds an Ext.Direct Provider and creates the proxy or stub methods to execute server-side methods.\r
298      * If the provider is not already connected, it will auto-connect.\r
299      * <pre><code>\r
300 var pollProv = new Ext.direct.PollingProvider({\r
301     url: 'php/poll2.php'\r
302 }); \r
303 \r
304 Ext.Direct.addProvider(\r
305     {\r
306         "type":"remoting",       // create a {@link Ext.direct.RemotingProvider} \r
307         "url":"php\/router.php", // url to connect to the Ext.Direct server-side router.\r
308         "actions":{              // each property within the actions object represents a Class \r
309             "TestAction":[       // array of methods within each server side Class   \r
310             {\r
311                 "name":"doEcho", // name of method\r
312                 "len":1\r
313             },{\r
314                 "name":"multiply",\r
315                 "len":1\r
316             },{\r
317                 "name":"doForm",\r
318                 "formHandler":true, // handle form on server with Ext.Direct.Transaction \r
319                 "len":1\r
320             }]\r
321         },\r
322         "namespace":"myApplication",// namespace to create the Remoting Provider in\r
323     },{\r
324         type: 'polling', // create a {@link Ext.direct.PollingProvider} \r
325         url:  'php/poll.php'\r
326     },\r
327     pollProv // reference to previously created instance\r
328 );\r
329      * </code></pre>\r
330      * @param {Object/Array} provider Accepts either an Array of Provider descriptions (an instance\r
331      * or config object for a Provider) or any number of Provider descriptions as arguments.  Each\r
332      * Provider description instructs Ext.Direct how to create client-side stub methods.\r
333      */\r
334     addProvider : function(provider){        \r
335         var a = arguments;\r
336         if(a.length > 1){\r
337             for(var i = 0, len = a.length; i < len; i++){\r
338                 this.addProvider(a[i]);\r
339             }\r
340             return;\r
341         }\r
342         \r
343         // if provider has not already been instantiated\r
344         if(!provider.events){\r
345             provider = new Ext.Direct.PROVIDERS[provider.type](provider);\r
346         }\r
347         provider.id = provider.id || Ext.id();\r
348         this.providers[provider.id] = provider;\r
349 \r
350         provider.on('data', this.onProviderData, this);\r
351         provider.on('exception', this.onProviderException, this);\r
352 \r
353 \r
354         if(!provider.isConnected()){\r
355             provider.connect();\r
356         }\r
357 \r
358         return provider;\r
359     },\r
360 \r
361     /**\r
362      * Retrieve a {@link Ext.direct.Provider provider} by the\r
363      * <b><tt>{@link Ext.direct.Provider#id id}</tt></b> specified when the provider is\r
364      * {@link #addProvider added}.\r
365      * @param {String} id Unique identifier assigned to the provider when calling {@link #addProvider} \r
366      */\r
367     getProvider : function(id){\r
368         return this.providers[id];\r
369     },\r
370 \r
371     removeProvider : function(id){\r
372         var provider = id.id ? id : this.providers[id.id];\r
373         provider.un('data', this.onProviderData, this);\r
374         provider.un('exception', this.onProviderException, this);\r
375         delete this.providers[provider.id];\r
376         return provider;\r
377     },\r
378 \r
379     addTransaction: function(t){\r
380         this.transactions[t.tid] = t;\r
381         return t;\r
382     },\r
383 \r
384     removeTransaction: function(t){\r
385         delete this.transactions[t.tid || t];\r
386         return t;\r
387     },\r
388 \r
389     getTransaction: function(tid){\r
390         return this.transactions[tid.tid || tid];\r
391     },\r
392 \r
393     onProviderData : function(provider, e){\r
394         if(Ext.isArray(e)){\r
395             for(var i = 0, len = e.length; i < len; i++){\r
396                 this.onProviderData(provider, e[i]);\r
397             }\r
398             return;\r
399         }\r
400         if(e.name && e.name != 'event' && e.name != 'exception'){\r
401             this.fireEvent(e.name, e);\r
402         }else if(e.type == 'exception'){\r
403             this.fireEvent('exception', e);\r
404         }\r
405         this.fireEvent('event', e, provider);\r
406     },\r
407 \r
408     createEvent : function(response, extraProps){\r
409         return new Ext.Direct.eventTypes[response.type](Ext.apply(response, extraProps));\r
410     }\r
411 });\r
412 // overwrite impl. with static instance\r
413 Ext.Direct = new Ext.Direct();\r
414 \r
415 Ext.Direct.TID = 1;\r
416 Ext.Direct.PROVIDERS = {};/**\r
417  * @class Ext.Direct.Transaction\r
418  * @extends Object\r
419  * <p>Supporting Class for Ext.Direct (not intended to be used directly).</p>\r
420  * @constructor\r
421  * @param {Object} config\r
422  */\r
423 Ext.Direct.Transaction = function(config){\r
424     Ext.apply(this, config);\r
425     this.tid = ++Ext.Direct.TID;\r
426     this.retryCount = 0;\r
427 };\r
428 Ext.Direct.Transaction.prototype = {\r
429     send: function(){\r
430         this.provider.queueTransaction(this);\r
431     },\r
432 \r
433     retry: function(){\r
434         this.retryCount++;\r
435         this.send();\r
436     },\r
437 \r
438     getProvider: function(){\r
439         return this.provider;\r
440     }\r
441 };Ext.Direct.Event = function(config){\r
442     Ext.apply(this, config);\r
443 }\r
444 Ext.Direct.Event.prototype = {\r
445     status: true,\r
446     getData: function(){\r
447         return this.data;\r
448     }\r
449 };\r
450 \r
451 Ext.Direct.RemotingEvent = Ext.extend(Ext.Direct.Event, {\r
452     type: 'rpc',\r
453     getTransaction: function(){\r
454         return this.transaction || Ext.Direct.getTransaction(this.tid);\r
455     }\r
456 });\r
457 \r
458 Ext.Direct.ExceptionEvent = Ext.extend(Ext.Direct.RemotingEvent, {\r
459     status: false,\r
460     type: 'exception'\r
461 });\r
462 \r
463 Ext.Direct.eventTypes = {\r
464     'rpc':  Ext.Direct.RemotingEvent,\r
465     'event':  Ext.Direct.Event,\r
466     'exception':  Ext.Direct.ExceptionEvent\r
467 };\r
468 \r
469 /**\r
470  * @class Ext.direct.Provider\r
471  * @extends Ext.util.Observable\r
472  * <p>Ext.direct.Provider is an abstract class meant to be extended.</p>\r
473  * \r
474  * <p>For example ExtJs implements the following subclasses:</p>\r
475  * <pre><code>\r
476 Provider\r
477 |\r
478 +---{@link Ext.direct.JsonProvider JsonProvider} \r
479     |\r
480     +---{@link Ext.direct.PollingProvider PollingProvider}   \r
481     |\r
482     +---{@link Ext.direct.RemotingProvider RemotingProvider}   \r
483  * </code></pre>\r
484  * @abstract\r
485  */\r
486 Ext.direct.Provider = Ext.extend(Ext.util.Observable, {    \r
487     /**\r
488      * @cfg {String} id\r
489      * The unique id of the provider (defaults to an {@link Ext#id auto-assigned id}).\r
490      * You should assign an id if you need to be able to access the provider later and you do\r
491      * not have an object reference available, for example:\r
492      * <pre><code>\r
493 Ext.Direct.addProvider(\r
494     {\r
495         type: 'polling',\r
496         url:  'php/poll.php',\r
497         id:   'poll-provider'\r
498     }\r
499 );\r
500      \r
501 var p = {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#getProvider getProvider}('poll-provider');\r
502 p.disconnect();\r
503      * </code></pre>\r
504      */\r
505         \r
506     /**\r
507      * @cfg {Number} priority\r
508      * Priority of the request. Lower is higher priority, <tt>0</tt> means "duplex" (always on).\r
509      * All Providers default to <tt>1</tt> except for PollingProvider which defaults to <tt>3</tt>.\r
510      */    \r
511     priority: 1,\r
512 \r
513     /**\r
514      * @cfg {String} type\r
515      * <b>Required</b>, <tt>undefined</tt> by default.  The <tt>type</tt> of provider specified\r
516      * to {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#addProvider addProvider} to create a\r
517      * new Provider. Acceptable values by default are:<div class="mdetail-params"><ul>\r
518      * <li><b><tt>polling</tt></b> : {@link Ext.direct.PollingProvider PollingProvider}</li>\r
519      * <li><b><tt>remoting</tt></b> : {@link Ext.direct.RemotingProvider RemotingProvider}</li>\r
520      * </ul></div>\r
521      */    \r
522  \r
523     // private\r
524     constructor : function(config){\r
525         Ext.apply(this, config);\r
526         this.addEvents(\r
527             /**\r
528              * @event connect\r
529              * Fires when the Provider connects to the server-side\r
530              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.\r
531              */            \r
532             'connect',\r
533             /**\r
534              * @event disconnect\r
535              * Fires when the Provider disconnects from the server-side\r
536              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.\r
537              */            \r
538             'disconnect',\r
539             /**\r
540              * @event data\r
541              * Fires when the Provider receives data from the server-side\r
542              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.\r
543              * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.\r
544              */            \r
545             'data',\r
546             /**\r
547              * @event exception\r
548              * Fires when the Provider receives an exception from the server-side\r
549              */                        \r
550             'exception'\r
551         );\r
552         Ext.direct.Provider.superclass.constructor.call(this, config);\r
553     },\r
554 \r
555     /**\r
556      * Returns whether or not the server-side is currently connected.\r
557      * Abstract method for subclasses to implement.\r
558      */\r
559     isConnected: function(){\r
560         return false;\r
561     },\r
562 \r
563     /**\r
564      * Abstract methods for subclasses to implement.\r
565      */\r
566     connect: Ext.emptyFn,\r
567     \r
568     /**\r
569      * Abstract methods for subclasses to implement.\r
570      */\r
571     disconnect: Ext.emptyFn\r
572 });\r
573 /**\r
574  * @class Ext.direct.JsonProvider\r
575  * @extends Ext.direct.Provider\r
576  */\r
577 Ext.direct.JsonProvider = Ext.extend(Ext.direct.Provider, {\r
578     parseResponse: function(xhr){\r
579         if(!Ext.isEmpty(xhr.responseText)){\r
580             if(typeof xhr.responseText == 'object'){\r
581                 return xhr.responseText;\r
582             }\r
583             return Ext.decode(xhr.responseText);\r
584         }\r
585         return null;\r
586     },\r
587 \r
588     getEvents: function(xhr){\r
589         var data = null;\r
590         try{\r
591             data = this.parseResponse(xhr);\r
592         }catch(e){\r
593             var event = new Ext.Direct.ExceptionEvent({\r
594                 data: e,\r
595                 xhr: xhr,\r
596                 code: Ext.Direct.exceptions.PARSE,\r
597                 message: 'Error parsing json response: \n\n ' + data\r
598             })\r
599             return [event];\r
600         }\r
601         var events = [];\r
602         if(Ext.isArray(data)){\r
603             for(var i = 0, len = data.length; i < len; i++){\r
604                 events.push(Ext.Direct.createEvent(data[i]));\r
605             }\r
606         }else{\r
607             events.push(Ext.Direct.createEvent(data));\r
608         }\r
609         return events;\r
610     }\r
611 });/**\r
612  * @class Ext.direct.PollingProvider\r
613  * @extends Ext.direct.JsonProvider\r
614  *\r
615  * <p>Provides for repetitive polling of the server at distinct {@link #interval intervals}.\r
616  * The initial request for data originates from the client, and then is responded to by the\r
617  * server.</p>\r
618  * \r
619  * <p>All configurations for the PollingProvider should be generated by the server-side\r
620  * API portion of the Ext.Direct stack.</p>\r
621  *\r
622  * <p>An instance of PollingProvider may be created directly via the new keyword or by simply\r
623  * specifying <tt>type = 'polling'</tt>.  For example:</p>\r
624  * <pre><code>\r
625 var pollA = new Ext.direct.PollingProvider({\r
626     type:'polling',\r
627     url: 'php/pollA.php',\r
628 });\r
629 Ext.Direct.addProvider(pollA);\r
630 pollA.disconnect();\r
631 \r
632 Ext.Direct.addProvider(\r
633     {\r
634         type:'polling',\r
635         url: 'php/pollB.php',\r
636         id: 'pollB-provider'\r
637     }\r
638 );\r
639 var pollB = Ext.Direct.getProvider('pollB-provider');\r
640  * </code></pre>\r
641  */\r
642 Ext.direct.PollingProvider = Ext.extend(Ext.direct.JsonProvider, {\r
643     /**\r
644      * @cfg {Number} priority\r
645      * Priority of the request (defaults to <tt>3</tt>). See {@link Ext.direct.Provider#priority}.\r
646      */\r
647     // override default priority\r
648     priority: 3,\r
649     \r
650     /**\r
651      * @cfg {Number} interval\r
652      * How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every\r
653      * 3 seconds).\r
654      */\r
655     interval: 3000,\r
656 \r
657     /**\r
658      * @cfg {Object} baseParams An object containing properties which are to be sent as parameters\r
659      * on every polling request\r
660      */\r
661     \r
662     /**\r
663      * @cfg {String/Function} url\r
664      * The url which the PollingProvider should contact with each request. This can also be\r
665      * an imported Ext.Direct method which will accept the baseParams as its only argument.\r
666      */\r
667 \r
668     // private\r
669     constructor : function(config){\r
670         Ext.direct.PollingProvider.superclass.constructor.call(this, config);\r
671         this.addEvents(\r
672             /**\r
673              * @event beforepoll\r
674              * Fired immediately before a poll takes place, an event handler can return false\r
675              * in order to cancel the poll.\r
676              * @param {Ext.direct.PollingProvider}\r
677              */\r
678             'beforepoll',            \r
679             /**\r
680              * @event poll\r
681              * This event has not yet been implemented.\r
682              * @param {Ext.direct.PollingProvider}\r
683              */\r
684             'poll'\r
685         );\r
686     },\r
687 \r
688     // inherited\r
689     isConnected: function(){\r
690         return !!this.pollTask;\r
691     },\r
692 \r
693     /**\r
694      * Connect to the server-side and begin the polling process. To handle each\r
695      * response subscribe to the data event.\r
696      */\r
697     connect: function(){\r
698         if(this.url && !this.pollTask){\r
699             this.pollTask = Ext.TaskMgr.start({\r
700                 run: function(){\r
701                     if(this.fireEvent('beforepoll', this) !== false){\r
702                         if(typeof this.url == 'function'){\r
703                             this.url(this.baseParams);\r
704                         }else{\r
705                             Ext.Ajax.request({\r
706                                 url: this.url,\r
707                                 callback: this.onData,\r
708                                 scope: this,\r
709                                 params: this.baseParams\r
710                             });\r
711                         }\r
712                     }\r
713                 },\r
714                 interval: this.interval,\r
715                 scope: this\r
716             });\r
717             this.fireEvent('connect', this);\r
718         }else if(!this.url){\r
719             throw 'Error initializing PollingProvider, no url configured.';\r
720         }\r
721     },\r
722 \r
723     /**\r
724      * Disconnect from the server-side and stop the polling process. The disconnect\r
725      * event will be fired on a successful disconnect.\r
726      */\r
727     disconnect: function(){\r
728         if(this.pollTask){\r
729             Ext.TaskMgr.stop(this.pollTask);\r
730             delete this.pollTask;\r
731             this.fireEvent('disconnect', this);\r
732         }\r
733     },\r
734 \r
735     // private\r
736     onData: function(opt, success, xhr){\r
737         if(success){\r
738             var events = this.getEvents(xhr);\r
739             for(var i = 0, len = events.length; i < len; i++){\r
740                 var e = events[i];\r
741                 this.fireEvent('data', this, e);\r
742             }\r
743         }else{\r
744             var e = new Ext.Direct.ExceptionEvent({\r
745                 data: e,\r
746                 code: Ext.Direct.exceptions.TRANSPORT,\r
747                 message: 'Unable to connect to the server.',\r
748                 xhr: xhr\r
749             });\r
750             this.fireEvent('data', this, e);\r
751         }\r
752     }\r
753 });\r
754 \r
755 Ext.Direct.PROVIDERS['polling'] = Ext.direct.PollingProvider;/**\r
756  * @class Ext.direct.RemotingProvider\r
757  * @extends Ext.direct.JsonProvider\r
758  * \r
759  * <p>The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to\r
760  * server side methods on the client (a remote procedure call (RPC) type of\r
761  * connection where the client can initiate a procedure on the server).</p>\r
762  * \r
763  * <p>This allows for code to be organized in a fashion that is maintainable,\r
764  * while providing a clear path between client and server, something that is\r
765  * not always apparent when using URLs.</p>\r
766  * \r
767  * <p>To accomplish this the server-side needs to describe what classes and methods\r
768  * are available on the client-side. This configuration will typically be\r
769  * outputted by the server-side Ext.Direct stack when the API description is built.</p>\r
770  */\r
771 Ext.direct.RemotingProvider = Ext.extend(Ext.direct.JsonProvider, {       \r
772     /**\r
773      * @cfg {Object} actions\r
774      * Object literal defining the server side actions and methods. For example, if\r
775      * the Provider is configured with:\r
776      * <pre><code>\r
777 "actions":{ // each property within the 'actions' object represents a server side Class \r
778     "TestAction":[ // array of methods within each server side Class to be   \r
779     {              // stubbed out on client\r
780         "name":"doEcho", \r
781         "len":1            \r
782     },{\r
783         "name":"multiply",// name of method\r
784         "len":2           // The number of parameters that will be used to create an\r
785                           // array of data to send to the server side function.\r
786                           // Ensure the server sends back a Number, not a String. \r
787     },{\r
788         "name":"doForm",\r
789         "formHandler":true, // direct the client to use specialized form handling method \r
790         "len":1\r
791     }]\r
792 }\r
793      * </code></pre>\r
794      * <p>Note that a Store is not required, a server method can be called at any time.\r
795      * In the following example a <b>client side</b> handler is used to call the\r
796      * server side method "multiply" in the server-side "TestAction" Class:</p>\r
797      * <pre><code>\r
798 TestAction.multiply(\r
799     2, 4, // pass two arguments to server, so specify len=2\r
800     // callback function after the server is called\r
801     // result: the result returned by the server\r
802     //      e: Ext.Direct.RemotingEvent object\r
803     function(result, e){\r
804         var t = e.getTransaction();\r
805         var action = t.action; // server side Class called\r
806         var method = t.method; // server side method called\r
807         if(e.status){\r
808             var answer = Ext.encode(result); // 8\r
809     \r
810         }else{\r
811             var msg = e.message; // failure message\r
812         }\r
813     }\r
814 );\r
815      * </code></pre>\r
816      * In the example above, the server side "multiply" function will be passed two\r
817      * arguments (2 and 4).  The "multiply" method should return the value 8 which will be\r
818      * available as the <tt>result</tt> in the example above. \r
819      */\r
820     \r
821     /**\r
822      * @cfg {String/Object} namespace\r
823      * Namespace for the Remoting Provider (defaults to the browser global scope of <i>window</i>).\r
824      * Explicitly specify the namespace Object, or specify a String to have a\r
825      * {@link Ext#namespace namespace created} implicitly.\r
826      */\r
827     \r
828     /**\r
829      * @cfg {String} url\r
830      * <b>Required<b>. The url to connect to the {@link Ext.Direct} server-side router. \r
831      */\r
832     \r
833     /**\r
834      * @cfg {String} enableUrlEncode\r
835      * Specify which param will hold the arguments for the method.\r
836      * Defaults to <tt>'data'</tt>.\r
837      */\r
838     \r
839     /**\r
840      * @cfg {Number/Boolean} enableBuffer\r
841      * <p><tt>true</tt> or <tt>false</tt> to enable or disable combining of method\r
842      * calls. If a number is specified this is the amount of time in milliseconds\r
843      * to wait before sending a batched request (defaults to <tt>10</tt>).</p>\r
844      * <br><p>Calls which are received within the specified timeframe will be\r
845      * concatenated together and sent in a single request, optimizing the\r
846      * application by reducing the amount of round trips that have to be made\r
847      * to the server.</p>\r
848      */\r
849     enableBuffer: 10,\r
850     \r
851     /**\r
852      * @cfg {Number} maxRetries\r
853      * Number of times to re-attempt delivery on failure of a call.\r
854      */\r
855     maxRetries: 1,\r
856 \r
857     constructor : function(config){\r
858         Ext.direct.RemotingProvider.superclass.constructor.call(this, config);\r
859         this.addEvents(\r
860             /**\r
861              * @event beforecall\r
862              * Fires immediately before the client-side sends off the RPC call.\r
863              * By returning false from an event handler you can prevent the call from\r
864              * executing.\r
865              * @param {Ext.direct.RemotingProvider} provider\r
866              * @param {Ext.Direct.Transaction} transaction\r
867              */            \r
868             'beforecall',\r
869             /**\r
870              * @event call\r
871              * Fires immediately after the request to the server-side is sent. This does\r
872              * NOT fire after the response has come back from the call.\r
873              * @param {Ext.direct.RemotingProvider} provider\r
874              * @param {Ext.Direct.Transaction} transaction\r
875              */            \r
876             'call'\r
877         );\r
878         this.namespace = (typeof this.namespace === 'string') ? Ext.ns(this.namespace) : this.namespace || window;\r
879         this.transactions = {};\r
880         this.callBuffer = [];\r
881     },\r
882 \r
883     // private\r
884     initAPI : function(){\r
885         var o = this.actions;\r
886         for(var c in o){\r
887             var cls = this.namespace[c] || (this.namespace[c] = {});\r
888             var ms = o[c];\r
889             for(var i = 0, len = ms.length; i < len; i++){\r
890                 var m = ms[i];\r
891                 cls[m.name] = this.createMethod(c, m);\r
892             }\r
893         }\r
894     },\r
895 \r
896     // inherited\r
897     isConnected: function(){\r
898         return !!this.connected;\r
899     },\r
900 \r
901     connect: function(){\r
902         if(this.url){\r
903             this.initAPI();\r
904             this.connected = true;\r
905             this.fireEvent('connect', this);\r
906         }else if(!this.url){\r
907             throw 'Error initializing RemotingProvider, no url configured.';\r
908         }\r
909     },\r
910 \r
911     disconnect: function(){\r
912         if(this.connected){\r
913             this.connected = false;\r
914             this.fireEvent('disconnect', this);\r
915         }\r
916     },\r
917 \r
918     onData: function(opt, success, xhr){\r
919         if(success){\r
920             var events = this.getEvents(xhr);\r
921             for(var i = 0, len = events.length; i < len; i++){\r
922                 var e = events[i];\r
923                 var t = this.getTransaction(e);\r
924                 this.fireEvent('data', this, e);\r
925                 if(t){\r
926                     this.doCallback(t, e, true);\r
927                     Ext.Direct.removeTransaction(t);\r
928                 }\r
929             }\r
930         }else{\r
931             var ts = [].concat(opt.ts);\r
932             for(var i = 0, len = ts.length; i < len; i++){\r
933                 var t = this.getTransaction(ts[i]);\r
934                 if(t && t.retryCount < this.maxRetries){\r
935                     t.retry();\r
936                 }else{\r
937                     var e = new Ext.Direct.ExceptionEvent({\r
938                         data: e,\r
939                         transaction: t,\r
940                         code: Ext.Direct.exceptions.TRANSPORT,\r
941                         message: 'Unable to connect to the server.',\r
942                         xhr: xhr\r
943                     });\r
944                     this.fireEvent('data', this, e);\r
945                     if(t){\r
946                         this.doCallback(t, e, false);\r
947                         Ext.Direct.removeTransaction(t);\r
948                     }\r
949                 }\r
950             }\r
951         }\r
952     },\r
953 \r
954     getCallData: function(t){\r
955         return {\r
956             action: t.action,\r
957             method: t.method,\r
958             data: t.data,\r
959             type: 'rpc',\r
960             tid: t.tid\r
961         };\r
962     },\r
963 \r
964     doSend : function(data){\r
965         var o = {\r
966             url: this.url,\r
967             callback: this.onData,\r
968             scope: this,\r
969             ts: data\r
970         };\r
971 \r
972         // send only needed data\r
973         var callData;\r
974         if(Ext.isArray(data)){\r
975             callData = [];\r
976             for(var i = 0, len = data.length; i < len; i++){\r
977                 callData.push(this.getCallData(data[i]));\r
978             }\r
979         }else{\r
980             callData = this.getCallData(data);\r
981         }\r
982 \r
983         if(this.enableUrlEncode){\r
984             var params = {};\r
985             params[typeof this.enableUrlEncode == 'string' ? this.enableUrlEncode : 'data'] = Ext.encode(callData);\r
986             o.params = params;\r
987         }else{\r
988             o.jsonData = callData;\r
989         }\r
990         Ext.Ajax.request(o);\r
991     },\r
992 \r
993     combineAndSend : function(){\r
994         var len = this.callBuffer.length;\r
995         if(len > 0){\r
996             this.doSend(len == 1 ? this.callBuffer[0] : this.callBuffer);\r
997             this.callBuffer = [];\r
998         }\r
999     },\r
1000 \r
1001     queueTransaction: function(t){\r
1002         if(t.form){\r
1003             this.processForm(t);\r
1004             return;\r
1005         }\r
1006         this.callBuffer.push(t);\r
1007         if(this.enableBuffer){\r
1008             if(!this.callTask){\r
1009                 this.callTask = new Ext.util.DelayedTask(this.combineAndSend, this);\r
1010             }\r
1011             this.callTask.delay(typeof this.enableBuffer == 'number' ? this.enableBuffer : 10);\r
1012         }else{\r
1013             this.combineAndSend();\r
1014         }\r
1015     },\r
1016 \r
1017     doCall : function(c, m, args){\r
1018         var data = null, hs = args[m.len], scope = args[m.len+1];\r
1019 \r
1020         if(m.len !== 0){\r
1021             data = args.slice(0, m.len);\r
1022         }\r
1023 \r
1024         var t = new Ext.Direct.Transaction({\r
1025             provider: this,\r
1026             args: args,\r
1027             action: c,\r
1028             method: m.name,\r
1029             data: data,\r
1030             cb: scope && Ext.isFunction(hs) ? hs.createDelegate(scope) : hs\r
1031         });\r
1032 \r
1033         if(this.fireEvent('beforecall', this, t) !== false){\r
1034             Ext.Direct.addTransaction(t);\r
1035             this.queueTransaction(t);\r
1036             this.fireEvent('call', this, t);\r
1037         }\r
1038     },\r
1039 \r
1040     doForm : function(c, m, form, callback, scope){\r
1041         var t = new Ext.Direct.Transaction({\r
1042             provider: this,\r
1043             action: c,\r
1044             method: m.name,\r
1045             args:[form, callback, scope],\r
1046             cb: scope && Ext.isFunction(callback) ? callback.createDelegate(scope) : callback,\r
1047             isForm: true\r
1048         });\r
1049 \r
1050         if(this.fireEvent('beforecall', this, t) !== false){\r
1051             Ext.Direct.addTransaction(t);\r
1052             var isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data',\r
1053                 params = {\r
1054                     extTID: t.tid,\r
1055                     extAction: c,\r
1056                     extMethod: m.name,\r
1057                     extType: 'rpc',\r
1058                     extUpload: String(isUpload)\r
1059                 };\r
1060             \r
1061             // change made from typeof callback check to callback.params\r
1062             // to support addl param passing in DirectSubmit EAC 6/2\r
1063             Ext.apply(t, {\r
1064                 form: Ext.getDom(form),\r
1065                 isUpload: isUpload,\r
1066                 params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params\r
1067             });\r
1068             this.fireEvent('call', this, t);\r
1069             this.processForm(t);\r
1070         }\r
1071     },\r
1072     \r
1073     processForm: function(t){\r
1074         Ext.Ajax.request({\r
1075             url: this.url,\r
1076             params: t.params,\r
1077             callback: this.onData,\r
1078             scope: this,\r
1079             form: t.form,\r
1080             isUpload: t.isUpload,\r
1081             ts: t\r
1082         });\r
1083     },\r
1084 \r
1085     createMethod : function(c, m){\r
1086         var f;\r
1087         if(!m.formHandler){\r
1088             f = function(){\r
1089                 this.doCall(c, m, Array.prototype.slice.call(arguments, 0));\r
1090             }.createDelegate(this);\r
1091         }else{\r
1092             f = function(form, callback, scope){\r
1093                 this.doForm(c, m, form, callback, scope);\r
1094             }.createDelegate(this);\r
1095         }\r
1096         f.directCfg = {\r
1097             action: c,\r
1098             method: m\r
1099         };\r
1100         return f;\r
1101     },\r
1102 \r
1103     getTransaction: function(opt){\r
1104         return opt && opt.tid ? Ext.Direct.getTransaction(opt.tid) : null;\r
1105     },\r
1106 \r
1107     doCallback: function(t, e){\r
1108         var fn = e.status ? 'success' : 'failure';\r
1109         if(t && t.cb){\r
1110             var hs = t.cb;\r
1111             var result = e.result || e.data;\r
1112             if(Ext.isFunction(hs)){\r
1113                 hs(result, e);\r
1114             } else{\r
1115                 Ext.callback(hs[fn], hs.scope, [result, e]);\r
1116                 Ext.callback(hs.callback, hs.scope, [result, e]);\r
1117             }\r
1118         }\r
1119     }\r
1120 });\r
1121 Ext.Direct.PROVIDERS['remoting'] = Ext.direct.RemotingProvider;