/hippo/src/main/webapp/ext/src/util/UpdateManager.js

http://hdbc.googlecode.com/ · JavaScript · 536 lines · 194 code · 32 blank · 310 comment · 34 complexity · 1229661a17c71f4cf2951574dd1572c3 MD5 · raw file

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