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