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