source: trunk/web/addons/job_monarch/lib/extjs/source/core/UpdateManager.js @ 619

Last change on this file since 619 was 619, checked in by ramonb, 15 years ago

lib/:

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