commit extjs-2.2.1
[extjs.git] / source / core / UpdateManager.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\r
10  * @class Ext.Updater\r
11  * @extends Ext.util.Observable\r
12  * Provides AJAX-style update capabilities for Element objects.  Updater can be used to {@link #update} an Element once,\r
13  * or you can use {@link #startAutoRefresh} to set up an auto-updating Element on a specific interval.<br><br>\r
14  * Usage:<br>\r
15  * <pre><code>\r
16  * // Get it from a Ext.Element object\r
17  * var el = Ext.get("foo");\r
18  * var mgr = el.getUpdater();\r
19  * mgr.update({\r
20         url: "http://myserver.com/index.php",\r
21         params: {\r
22             param1: "foo",\r
23             param2: "bar"\r
24         }\r
25  * });\r
26  * ...\r
27  * mgr.formUpdate("myFormId", "http://myserver.com/index.php");\r
28  * <br>\r
29  * // or directly (returns the same Updater instance)\r
30  * var mgr = new Ext.Updater("myElementId");\r
31  * mgr.startAutoRefresh(60, "http://myserver.com/index.php");\r
32  * mgr.on("update", myFcnNeedsToKnow);\r
33  * <br>\r
34  * // short handed call directly from the element object\r
35  * Ext.get("foo").load({\r
36         url: "bar.php",\r
37         scripts: true,\r
38         params: "param1=foo&amp;param2=bar",\r
39         text: "Loading Foo..."\r
40  * });\r
41  * </code></pre>\r
42  * @constructor\r
43  * Create new Updater directly.\r
44  * @param {Mixed} el The element to update\r
45  * @param {Boolean} forceNew (optional) By default the constructor checks to see if the passed element already\r
46  * has an Updater and if it does it returns the same instance. This will skip that check (useful for extending this class).\r
47  */\r
48 Ext.Updater = Ext.extend(Ext.util.Observable, {\r
49     constructor: function(el, forceNew){\r
50         el = Ext.get(el);\r
51         if(!forceNew && el.updateManager){\r
52             return el.updateManager;\r
53         }\r
54         /**\r
55          * The Element object\r
56          * @type Ext.Element\r
57          */\r
58         this.el = el;\r
59         /**\r
60          * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.\r
61          * @type String\r
62          */\r
63         this.defaultUrl = null;\r
64 \r
65         this.addEvents(\r
66             /**\r
67              * @event beforeupdate\r
68              * Fired before an update is made, return false from your handler and the update is cancelled.\r
69              * @param {Ext.Element} el\r
70              * @param {String/Object/Function} url\r
71              * @param {String/Object} params\r
72              */\r
73             "beforeupdate",\r
74             /**\r
75              * @event update\r
76              * Fired after successful update is made.\r
77              * @param {Ext.Element} el\r
78              * @param {Object} oResponseObject The response Object\r
79              */\r
80             "update",\r
81             /**\r
82              * @event failure\r
83              * Fired on update failure.\r
84              * @param {Ext.Element} el\r
85              * @param {Object} oResponseObject The response Object\r
86              */\r
87             "failure"\r
88         );\r
89         var d = Ext.Updater.defaults;\r
90         /**\r
91          * Blank page URL to use with SSL file uploads (defaults to {@link Ext.Updater.defaults#sslBlankUrl}).\r
92          * @type String\r
93          */\r
94         this.sslBlankUrl = d.sslBlankUrl;\r
95         /**\r
96          * Whether to append unique parameter on get request to disable caching (defaults to {@link Ext.Updater.defaults#disableCaching}).\r
97          * @type Boolean\r
98          */\r
99         this.disableCaching = d.disableCaching;\r
100         /**\r
101          * Text for loading indicator (defaults to {@link Ext.Updater.defaults#indicatorText}).\r
102          * @type String\r
103          */\r
104         this.indicatorText = d.indicatorText;\r
105         /**\r
106          * Whether to show indicatorText when loading (defaults to {@link Ext.Updater.defaults#showLoadIndicator}).\r
107          * @type String\r
108          */\r
109         this.showLoadIndicator = d.showLoadIndicator;\r
110         /**\r
111          * Timeout for requests or form posts in seconds (defaults to {@link Ext.Updater.defaults#timeout}).\r
112          * @type Number\r
113          */\r
114         this.timeout = d.timeout;\r
115         /**\r
116          * True to process scripts in the output (defaults to {@link Ext.Updater.defaults#loadScripts}).\r
117          * @type Boolean\r
118          */\r
119         this.loadScripts = d.loadScripts;\r
120         /**\r
121          * Transaction object of the current executing transaction, or null if there is no active transaction.\r
122          */\r
123         this.transaction = null;\r
124         /**\r
125          * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments\r
126          * @type Function\r
127          */\r
128         this.refreshDelegate = this.refresh.createDelegate(this);\r
129         /**\r
130          * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments\r
131          * @type Function\r
132          */\r
133         this.updateDelegate = this.update.createDelegate(this);\r
134         /**\r
135          * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments\r
136          * @type Function\r
137          */\r
138         this.formUpdateDelegate = this.formUpdate.createDelegate(this);\r
139 \r
140         if(!this.renderer){\r
141          /**\r
142           * The renderer for this Updater (defaults to {@link Ext.Updater.BasicRenderer}).\r
143           */\r
144         this.renderer = this.getDefaultRenderer();\r
145         }\r
146         Ext.Updater.superclass.constructor.call(this);\r
147     },\r
148     /**\r
149      * This is an overrideable method which returns a reference to a default\r
150      * renderer class if none is specified when creating the Ext.Updater.\r
151      * Defaults to {@link Ext.Updater.BasicRenderer}\r
152      */\r
153     getDefaultRenderer: function() {\r
154         return new Ext.Updater.BasicRenderer();\r
155     },\r
156     /**\r
157      * Get the Element this Updater is bound to\r
158      * @return {Ext.Element} The element\r
159      */\r
160     getEl : function(){\r
161         return this.el;\r
162     },\r
163 \r
164     /**\r
165      * Performs an <b>asynchronous</b> request, updating this element with the response.\r
166      * If params are specified it uses POST, otherwise it uses GET.<br><br>\r
167      * <b>Note:</b> Due to the asynchronous nature of remote server requests, the Element\r
168      * will not have been fully updated when the function returns. To post-process the returned\r
169      * data, use the callback option, or an <b><tt>update</tt></b> event handler.\r
170      * @param {Object} options A config object containing any of the following options:<ul>\r
171      * <li>url : <b>String/Function</b><p class="sub-desc">The URL to request or a function which\r
172      * <i>returns</i> the URL (defaults to the value of {@link Ext.Ajax#url} if not specified).</p></li>\r
173      * <li>method : <b>String</b><p class="sub-desc">The HTTP method to\r
174      * use. Defaults to POST if the <tt>params</tt> argument is present, otherwise GET.</p></li>\r
175      * <li>params : <b>String/Object/Function</b><p class="sub-desc">The\r
176      * parameters to pass to the server (defaults to none). These may be specified as a url-encoded\r
177      * string, or as an object containing properties which represent parameters,\r
178      * or as a function, which returns such an object.</p></li>\r
179      * <li>scripts : <b>Boolean</b><p class="sub-desc">If <tt>true</tt>\r
180      * any &lt;script&gt; tags embedded in the response text will be extracted\r
181      * and executed (defaults to {@link Ext.Updater.defaults#loadScripts}). If this option is specified,\r
182      * the callback will be called <i>after</i> the execution of the scripts.</p></li>\r
183      * <li>callback : <b>Function</b><p class="sub-desc">A function to\r
184      * be called when the response from the server arrives. The following\r
185      * parameters are passed:<ul>\r
186      * <li><b>el</b> : Ext.Element<p class="sub-desc">The Element being updated.</p></li>\r
187      * <li><b>success</b> : Boolean<p class="sub-desc">True for success, false for failure.</p></li>\r
188      * <li><b>response</b> : XMLHttpRequest<p class="sub-desc">The XMLHttpRequest which processed the update.</p></li>\r
189      * <li><b>options</b> : Object<p class="sub-desc">The config object passed to the update call.</p></li></ul>\r
190      * </p></li>\r
191      * <li>scope : <b>Object</b><p class="sub-desc">The scope in which\r
192      * to execute the callback (The callback's <tt>this</tt> reference.) If the\r
193      * <tt>params</tt> argument is a function, this scope is used for that function also.</p></li>\r
194      * <li>discardUrl : <b>Boolean</b><p class="sub-desc">By default, the URL of this request becomes\r
195      * the default URL for this Updater object, and will be subsequently used in {@link #refresh}\r
196      * calls.  To bypass this behavior, pass <tt>discardUrl:true</tt> (defaults to false).</p></li>\r
197      * <li>timeout : <b>Number</b><p class="sub-desc">The number of seconds to wait for a response before\r
198      * timing out (defaults to {@link Ext.Updater.defaults#timeout}).</p></li>\r
199      * <li>text : <b>String</b><p class="sub-desc">The text to use as the innerHTML of the\r
200      * {@link Ext.Updater.defaults#indicatorText} div (defaults to 'Loading...').  To replace the entire div, not\r
201      * just the text, override {@link Ext.Updater.defaults#indicatorText} directly.</p></li>\r
202      * <li>nocache : <b>Boolean</b><p class="sub-desc">Only needed for GET\r
203      * requests, this option causes an extra, auto-generated parameter to be appended to the request\r
204      * to defeat caching (defaults to {@link Ext.Updater.defaults#disableCaching}).</p></li></ul>\r
205      * <p>\r
206      * For example:\r
207 <pre><code>\r
208 um.update({\r
209     url: "your-url.php",\r
210     params: {param1: "foo", param2: "bar"}, // or a URL encoded string\r
211     callback: yourFunction,\r
212     scope: yourObject, //(optional scope)\r
213     discardUrl: true,\r
214     nocache: true,\r
215     text: "Loading...",\r
216     timeout: 60,\r
217     scripts: false // Save time by avoiding RegExp execution.\r
218 });\r
219 </code></pre>\r
220      */\r
221     update : function(url, params, callback, discardUrl){\r
222         if(this.fireEvent("beforeupdate", this.el, url, params) !== false){\r
223             var cfg, callerScope;\r
224             if(typeof url == "object"){ // must be config object\r
225                 cfg = url;\r
226                 url = cfg.url;\r
227                 params = params || cfg.params;\r
228                 callback = callback || cfg.callback;\r
229                 discardUrl = discardUrl || cfg.discardUrl;\r
230                 callerScope = cfg.scope;\r
231                 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};\r
232                 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};\r
233                 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};\r
234                 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};\r
235             }\r
236             this.showLoading();\r
237 \r
238             if(!discardUrl){\r
239                 this.defaultUrl = url;\r
240             }\r
241             if(typeof url == "function"){\r
242                 url = url.call(this);\r
243             }\r
244 \r
245             var o = Ext.apply({}, {\r
246                 url : url,\r
247                 params: (typeof params == "function" && callerScope) ? params.createDelegate(callerScope) : params,\r
248                 success: this.processSuccess,\r
249                 failure: this.processFailure,\r
250                 scope: this,\r
251                 callback: undefined,\r
252                 timeout: (this.timeout*1000),\r
253                 disableCaching: this.disableCaching,\r
254                 argument: {\r
255                     "options": cfg,\r
256                     "url": url,\r
257                     "form": null,\r
258                     "callback": callback,\r
259                     "scope": callerScope || window,\r
260                     "params": params\r
261                 }\r
262             }, cfg);\r
263 \r
264             this.transaction = Ext.Ajax.request(o);\r
265         }\r
266     },\r
267 \r
268     /**\r
269      * <p>Performs an async form post, updating this element with the response. If the form has the attribute\r
270      * enctype="<a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>", it assumes it's a file upload.\r
271      * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.</p>\r
272      * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>\r
273      * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the\r
274      * DOM <tt>&lt;form></tt> element temporarily modified to have its\r
275      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer\r
276      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document\r
277      * but removed after the return data has been gathered.</p>\r
278      * <p>Be aware that file upload packets, sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>\r
279      * and some server technologies (notably JEE) may require some custom processing in order to\r
280      * retrieve parameter names and parameter values from the packet content.</p>\r
281      * @param {String/HTMLElement} form The form Id or form element\r
282      * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.\r
283      * @param {Boolean} reset (optional) Whether to try to reset the form after the update\r
284      * @param {Function} callback (optional) Callback when transaction is complete. The following\r
285      * parameters are passed:<ul>\r
286      * <li><b>el</b> : Ext.Element<p class="sub-desc">The Element being updated.</p></li>\r
287      * <li><b>success</b> : Boolean<p class="sub-desc">True for success, false for failure.</p></li>\r
288      * <li><b>response</b> : XMLHttpRequest<p class="sub-desc">The XMLHttpRequest which processed the update.</p></li></ul>\r
289      */\r
290     formUpdate : function(form, url, reset, callback){\r
291         if(this.fireEvent("beforeupdate", this.el, form, url) !== false){\r
292             if(typeof url == "function"){\r
293                 url = url.call(this);\r
294             }\r
295             form = Ext.getDom(form)\r
296             this.transaction = Ext.Ajax.request({\r
297                 form: form,\r
298                 url:url,\r
299                 success: this.processSuccess,\r
300                 failure: this.processFailure,\r
301                 scope: this,\r
302                 timeout: (this.timeout*1000),\r
303                 argument: {\r
304                     "url": url,\r
305                     "form": form,\r
306                     "callback": callback,\r
307                     "reset": reset\r
308                 }\r
309             });\r
310             this.showLoading.defer(1, this);\r
311         }\r
312     },\r
313 \r
314     /**\r
315      * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately\r
316      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)\r
317      */\r
318     refresh : function(callback){\r
319         if(this.defaultUrl == null){\r
320             return;\r
321         }\r
322         this.update(this.defaultUrl, null, callback, true);\r
323     },\r
324 \r
325     /**\r
326      * Set this element to auto refresh.  Can be canceled by calling {@link #stopAutoRefresh}.\r
327      * @param {Number} interval How often to update (in seconds).\r
328      * @param {String/Object/Function} url (optional) The url for this request, a config object in the same format\r
329      * supported by {@link #load}, or a function to call to get the url (defaults to the last used url).  Note that while\r
330      * the url used in a load call can be reused by this method, other load config options will not be reused and must be\r
331      * sepcified as part of a config object passed as this paramter if needed.\r
332      * @param {String/Object} params (optional) The parameters to pass as either a url encoded string\r
333      * "&param1=1&param2=2" or as an object {param1: 1, param2: 2}\r
334      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)\r
335      * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval\r
336      */\r
337     startAutoRefresh : function(interval, url, params, callback, refreshNow){\r
338         if(refreshNow){\r
339             this.update(url || this.defaultUrl, params, callback, true);\r
340         }\r
341         if(this.autoRefreshProcId){\r
342             clearInterval(this.autoRefreshProcId);\r
343         }\r
344         this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);\r
345     },\r
346 \r
347     /**\r
348      * Stop auto refresh on this element.\r
349      */\r
350      stopAutoRefresh : function(){\r
351         if(this.autoRefreshProcId){\r
352             clearInterval(this.autoRefreshProcId);\r
353             delete this.autoRefreshProcId;\r
354         }\r
355     },\r
356 \r
357     /**\r
358      * Returns true if the Updater is currently set to auto refresh its content (see {@link #startAutoRefresh}), otherwise false.\r
359      */\r
360     isAutoRefreshing : function(){\r
361        return this.autoRefreshProcId ? true : false;\r
362     },\r
363 \r
364     /**\r
365      * Display the element's "loading" state. By default, the element is updated with {@link #indicatorText}. This\r
366      * method may be overridden to perform a custom action while this Updater is actively updating its contents.\r
367      */\r
368     showLoading : function(){\r
369         if(this.showLoadIndicator){\r
370             this.el.update(this.indicatorText);\r
371         }\r
372     },\r
373 \r
374     // private\r
375     processSuccess : function(response){\r
376         this.transaction = null;\r
377         if(response.argument.form && response.argument.reset){\r
378             try{ // put in try/catch since some older FF releases had problems with this\r
379                 response.argument.form.reset();\r
380             }catch(e){}\r
381         }\r
382         if(this.loadScripts){\r
383             this.renderer.render(this.el, response, this,\r
384                 this.updateComplete.createDelegate(this, [response]));\r
385         }else{\r
386             this.renderer.render(this.el, response, this);\r
387             this.updateComplete(response);\r
388         }\r
389     },\r
390 \r
391     // private\r
392     updateComplete : function(response){\r
393         this.fireEvent("update", this.el, response);\r
394         if(typeof response.argument.callback == "function"){\r
395             response.argument.callback.call(response.argument.scope, this.el, true, response, response.argument.options);\r
396         }\r
397     },\r
398 \r
399     // private\r
400     processFailure : function(response){\r
401         this.transaction = null;\r
402         this.fireEvent("failure", this.el, response);\r
403         if(typeof response.argument.callback == "function"){\r
404             response.argument.callback.call(response.argument.scope, this.el, false, response, response.argument.options);\r
405         }\r
406     },\r
407 \r
408     /**\r
409      * Sets the content renderer for this Updater. See {@link Ext.Updater.BasicRenderer#render} for more details.\r
410      * @param {Object} renderer The object implementing the render() method\r
411      */\r
412     setRenderer : function(renderer){\r
413         this.renderer = renderer;\r
414     },\r
415 \r
416     /**\r
417      * Returns the content renderer for this Updater. See {@link Ext.Updater.BasicRenderer#render} for more details.\r
418      * @return {Object}\r
419      */\r
420     getRenderer : function(){\r
421        return this.renderer;\r
422     },\r
423 \r
424     /**\r
425      * Sets the default URL used for updates.\r
426      * @param {String/Function} defaultUrl The url or a function to call to get the url\r
427      */\r
428     setDefaultUrl : function(defaultUrl){\r
429         this.defaultUrl = defaultUrl;\r
430     },\r
431 \r
432     /**\r
433      * Aborts the currently executing transaction, if any.\r
434      */\r
435     abort : function(){\r
436         if(this.transaction){\r
437             Ext.Ajax.abort(this.transaction);\r
438         }\r
439     },\r
440 \r
441     /**\r
442      * Returns true if an update is in progress, otherwise false.\r
443      * @return {Boolean}\r
444      */\r
445     isUpdating : function(){\r
446         if(this.transaction){\r
447             return Ext.Ajax.isLoading(this.transaction);\r
448         }\r
449         return false;\r
450     }\r
451 });\r
452 \r
453 /**\r
454  * @class Ext.Updater.defaults\r
455  * The defaults collection enables customizing the default properties of Updater\r
456  */\r
457    Ext.Updater.defaults = {\r
458        /**\r
459          * Timeout for requests or form posts in seconds (defaults to 30 seconds).\r
460          * @type Number\r
461          */\r
462          timeout : 30,\r
463          /**\r
464          * True to process scripts by default (defaults to false).\r
465          * @type Boolean\r
466          */\r
467         loadScripts : false,\r
468         /**\r
469         * Blank page URL to use with SSL file uploads (defaults to {@link Ext#SSL_SECURE_URL} if set, or "javascript:false").\r
470         * @type String\r
471         */\r
472         sslBlankUrl : (Ext.SSL_SECURE_URL || "javascript:false"),\r
473         /**\r
474          * True to append a unique parameter to GET requests to disable caching (defaults to false).\r
475          * @type Boolean\r
476          */\r
477         disableCaching : false,\r
478         /**\r
479          * Whether or not to show {@link #indicatorText} during loading (defaults to true).\r
480          * @type Boolean\r
481          */\r
482         showLoadIndicator : true,\r
483         /**\r
484          * Text for loading indicator (defaults to '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').\r
485          * @type String\r
486          */\r
487         indicatorText : '<div class="loading-indicator">Loading...</div>'\r
488    };\r
489 \r
490 /**\r
491  * Static convenience method. <b>This method is deprecated in favor of el.load({url:'foo.php', ...})</b>.\r
492  * Usage:\r
493  * <pre><code>Ext.Updater.updateElement("my-div", "stuff.php");</code></pre>\r
494  * @param {Mixed} el The element to update\r
495  * @param {String} url The url\r
496  * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs\r
497  * @param {Object} options (optional) A config object with any of the Updater properties you want to set - for\r
498  * example: {disableCaching:true, indicatorText: "Loading data..."}\r
499  * @static\r
500  * @deprecated\r
501  * @member Ext.Updater\r
502  */\r
503 Ext.Updater.updateElement = function(el, url, params, options){\r
504     var um = Ext.get(el).getUpdater();\r
505     Ext.apply(um, options);\r
506     um.update(url, params, options ? options.callback : null);\r
507 };\r
508 /**\r
509  * @class Ext.Updater.BasicRenderer\r
510  * Default Content renderer. Updates the elements innerHTML with the responseText.\r
511  */\r
512 Ext.Updater.BasicRenderer = function(){};\r
513 \r
514 Ext.Updater.BasicRenderer.prototype = {\r
515     /**\r
516      * This is called when the transaction is completed and it's time to update the element - The BasicRenderer\r
517      * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),\r
518      * create an object with a "render(el, response)" method and pass it to setRenderer on the Updater.\r
519      * @param {Ext.Element} el The element being rendered\r
520      * @param {Object} response The XMLHttpRequest object\r
521      * @param {Updater} updateManager The calling update manager\r
522      * @param {Function} callback A callback that will need to be called if loadScripts is true on the Updater\r
523      */\r
524      render : function(el, response, updateManager, callback){\r
525         el.update(response.responseText, updateManager.loadScripts, callback);\r
526     }\r
527 };\r
528 \r
529 Ext.UpdateManager = Ext.Updater;\r