[ Index ] |
PHP Cross Reference of Unnamed Project |
[Summary view] [Print] [Text view]
1 YUI.add('yui2-datasource', function(Y) { 2 var YAHOO = Y.YUI2; 3 /* 4 Copyright (c) 2011, Yahoo! Inc. All rights reserved. 5 Code licensed under the BSD License: 6 http://developer.yahoo.com/yui/license.html 7 version: 2.9.0 8 */ 9 (function () { 10 11 var lang = YAHOO.lang, 12 util = YAHOO.util, 13 Ev = util.Event; 14 15 /** 16 * The DataSource utility provides a common configurable interface for widgets to 17 * access a variety of data, from JavaScript arrays to online database servers. 18 * 19 * @module datasource 20 * @requires yahoo, event 21 * @optional json, get, connection 22 * @title DataSource Utility 23 */ 24 25 /****************************************************************************/ 26 /****************************************************************************/ 27 /****************************************************************************/ 28 29 /** 30 * Base class for the YUI DataSource utility. 31 * 32 * @namespace YAHOO.util 33 * @class YAHOO.util.DataSourceBase 34 * @constructor 35 * @param oLiveData {HTMLElement} Pointer to live data. 36 * @param oConfigs {object} (optional) Object literal of configuration values. 37 */ 38 util.DataSourceBase = function(oLiveData, oConfigs) { 39 if(oLiveData === null || oLiveData === undefined) { 40 YAHOO.log("Could not instantiate DataSource due to invalid live database", 41 "error", this.toString()); 42 return; 43 } 44 45 this.liveData = oLiveData; 46 this._oQueue = {interval:null, conn:null, requests:[]}; 47 this.responseSchema = {}; 48 49 // Set any config params passed in to override defaults 50 if(oConfigs && (oConfigs.constructor == Object)) { 51 for(var sConfig in oConfigs) { 52 if(sConfig) { 53 this[sConfig] = oConfigs[sConfig]; 54 } 55 } 56 } 57 58 // Validate and initialize public configs 59 var maxCacheEntries = this.maxCacheEntries; 60 if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) { 61 maxCacheEntries = 0; 62 } 63 64 // Initialize interval tracker 65 this._aIntervals = []; 66 67 ///////////////////////////////////////////////////////////////////////////// 68 // 69 // Custom Events 70 // 71 ///////////////////////////////////////////////////////////////////////////// 72 73 /** 74 * Fired when a request is made to the local cache. 75 * 76 * @event cacheRequestEvent 77 * @param oArgs.request {Object} The request object. 78 * @param oArgs.callback {Object} The callback object. 79 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 80 */ 81 this.createEvent("cacheRequestEvent"); 82 83 /** 84 * Fired when data is retrieved from the local cache. 85 * 86 * @event cacheResponseEvent 87 * @param oArgs.request {Object} The request object. 88 * @param oArgs.response {Object} The response object. 89 * @param oArgs.callback {Object} The callback object. 90 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 91 */ 92 this.createEvent("cacheResponseEvent"); 93 94 /** 95 * Fired when a request is sent to the live data source. 96 * 97 * @event requestEvent 98 * @param oArgs.request {Object} The request object. 99 * @param oArgs.callback {Object} The callback object. 100 * @param oArgs.tId {Number} Transaction ID. 101 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 102 */ 103 this.createEvent("requestEvent"); 104 105 /** 106 * Fired when live data source sends response. 107 * 108 * @event responseEvent 109 * @param oArgs.request {Object} The request object. 110 * @param oArgs.response {Object} The raw response object. 111 * @param oArgs.callback {Object} The callback object. 112 * @param oArgs.tId {Number} Transaction ID. 113 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 114 */ 115 this.createEvent("responseEvent"); 116 117 /** 118 * Fired when response is parsed. 119 * 120 * @event responseParseEvent 121 * @param oArgs.request {Object} The request object. 122 * @param oArgs.response {Object} The parsed response object. 123 * @param oArgs.callback {Object} The callback object. 124 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 125 */ 126 this.createEvent("responseParseEvent"); 127 128 /** 129 * Fired when response is cached. 130 * 131 * @event responseCacheEvent 132 * @param oArgs.request {Object} The request object. 133 * @param oArgs.response {Object} The parsed response object. 134 * @param oArgs.callback {Object} The callback object. 135 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 136 */ 137 this.createEvent("responseCacheEvent"); 138 /** 139 * Fired when an error is encountered with the live data source. 140 * 141 * @event dataErrorEvent 142 * @param oArgs.request {Object} The request object. 143 * @param oArgs.response {String} The response object (if available). 144 * @param oArgs.callback {Object} The callback object. 145 * @param oArgs.caller {Object} (deprecated) Use callback.scope. 146 * @param oArgs.message {String} The error message. 147 */ 148 this.createEvent("dataErrorEvent"); 149 150 /** 151 * Fired when the local cache is flushed. 152 * 153 * @event cacheFlushEvent 154 */ 155 this.createEvent("cacheFlushEvent"); 156 157 var DS = util.DataSourceBase; 158 this._sName = "DataSource instance" + DS._nIndex; 159 DS._nIndex++; 160 YAHOO.log("DataSource initialized", "info", this.toString()); 161 }; 162 163 var DS = util.DataSourceBase; 164 165 lang.augmentObject(DS, { 166 167 ///////////////////////////////////////////////////////////////////////////// 168 // 169 // DataSourceBase public constants 170 // 171 ///////////////////////////////////////////////////////////////////////////// 172 173 /** 174 * Type is unknown. 175 * 176 * @property TYPE_UNKNOWN 177 * @type Number 178 * @final 179 * @default -1 180 */ 181 TYPE_UNKNOWN : -1, 182 183 /** 184 * Type is a JavaScript Array. 185 * 186 * @property TYPE_JSARRAY 187 * @type Number 188 * @final 189 * @default 0 190 */ 191 TYPE_JSARRAY : 0, 192 193 /** 194 * Type is a JavaScript Function. 195 * 196 * @property TYPE_JSFUNCTION 197 * @type Number 198 * @final 199 * @default 1 200 */ 201 TYPE_JSFUNCTION : 1, 202 203 /** 204 * Type is hosted on a server via an XHR connection. 205 * 206 * @property TYPE_XHR 207 * @type Number 208 * @final 209 * @default 2 210 */ 211 TYPE_XHR : 2, 212 213 /** 214 * Type is JSON. 215 * 216 * @property TYPE_JSON 217 * @type Number 218 * @final 219 * @default 3 220 */ 221 TYPE_JSON : 3, 222 223 /** 224 * Type is XML. 225 * 226 * @property TYPE_XML 227 * @type Number 228 * @final 229 * @default 4 230 */ 231 TYPE_XML : 4, 232 233 /** 234 * Type is plain text. 235 * 236 * @property TYPE_TEXT 237 * @type Number 238 * @final 239 * @default 5 240 */ 241 TYPE_TEXT : 5, 242 243 /** 244 * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements. 245 * 246 * @property TYPE_HTMLTABLE 247 * @type Number 248 * @final 249 * @default 6 250 */ 251 TYPE_HTMLTABLE : 6, 252 253 /** 254 * Type is hosted on a server via a dynamic script node. 255 * 256 * @property TYPE_SCRIPTNODE 257 * @type Number 258 * @final 259 * @default 7 260 */ 261 TYPE_SCRIPTNODE : 7, 262 263 /** 264 * Type is local. 265 * 266 * @property TYPE_LOCAL 267 * @type Number 268 * @final 269 * @default 8 270 */ 271 TYPE_LOCAL : 8, 272 273 /** 274 * Error message for invalid dataresponses. 275 * 276 * @property ERROR_DATAINVALID 277 * @type String 278 * @final 279 * @default "Invalid data" 280 */ 281 ERROR_DATAINVALID : "Invalid data", 282 283 /** 284 * Error message for null data responses. 285 * 286 * @property ERROR_DATANULL 287 * @type String 288 * @final 289 * @default "Null data" 290 */ 291 ERROR_DATANULL : "Null data", 292 293 ///////////////////////////////////////////////////////////////////////////// 294 // 295 // DataSourceBase private static properties 296 // 297 ///////////////////////////////////////////////////////////////////////////// 298 299 /** 300 * Internal class variable to index multiple DataSource instances. 301 * 302 * @property DataSourceBase._nIndex 303 * @type Number 304 * @private 305 * @static 306 */ 307 _nIndex : 0, 308 309 /** 310 * Internal class variable to assign unique transaction IDs. 311 * 312 * @property DataSourceBase._nTransactionId 313 * @type Number 314 * @private 315 * @static 316 */ 317 _nTransactionId : 0, 318 319 ///////////////////////////////////////////////////////////////////////////// 320 // 321 // DataSourceBase private static methods 322 // 323 ///////////////////////////////////////////////////////////////////////////// 324 /** 325 * Clones object literal or array of object literals. 326 * 327 * @method DataSourceBase._cloneObject 328 * @param o {Object} Object. 329 * @private 330 * @static 331 */ 332 _cloneObject: function(o) { 333 if(!lang.isValue(o)) { 334 return o; 335 } 336 337 var copy = {}; 338 339 if(Object.prototype.toString.apply(o) === "[object RegExp]") { 340 copy = o; 341 } 342 else if(lang.isFunction(o)) { 343 copy = o; 344 } 345 else if(lang.isArray(o)) { 346 var array = []; 347 for(var i=0,len=o.length;i<len;i++) { 348 array[i] = DS._cloneObject(o[i]); 349 } 350 copy = array; 351 } 352 else if(lang.isObject(o)) { 353 for (var x in o){ 354 if(lang.hasOwnProperty(o, x)) { 355 if(lang.isValue(o[x]) && lang.isObject(o[x]) || lang.isArray(o[x])) { 356 copy[x] = DS._cloneObject(o[x]); 357 } 358 else { 359 copy[x] = o[x]; 360 } 361 } 362 } 363 } 364 else { 365 copy = o; 366 } 367 368 return copy; 369 }, 370 371 /** 372 * Get an XPath-specified value for a given field from an XML node or document. 373 * 374 * @method _getLocationValue 375 * @param field {String | Object} Field definition. 376 * @param context {Object} XML node or document to search within. 377 * @return {Object} Data value or null. 378 * @static 379 * @private 380 */ 381 _getLocationValue: function(field, context) { 382 var locator = field.locator || field.key || field, 383 xmldoc = context.ownerDocument || context, 384 result, res, value = null; 385 386 try { 387 // Standards mode 388 if(!lang.isUndefined(xmldoc.evaluate)) { 389 result = xmldoc.evaluate(locator, context, xmldoc.createNSResolver(!context.ownerDocument ? context.documentElement : context.ownerDocument.documentElement), 0, null); 390 while(res = result.iterateNext()) { 391 value = res.textContent; 392 } 393 } 394 // IE mode 395 else { 396 xmldoc.setProperty("SelectionLanguage", "XPath"); 397 result = context.selectNodes(locator)[0]; 398 value = result.value || result.text || null; 399 } 400 return value; 401 402 } 403 catch(e) { 404 } 405 }, 406 407 ///////////////////////////////////////////////////////////////////////////// 408 // 409 // DataSourceBase public static methods 410 // 411 ///////////////////////////////////////////////////////////////////////////// 412 413 /** 414 * Executes a configured callback. For object literal callbacks, the third 415 * param determines whether to execute the success handler or failure handler. 416 * 417 * @method issueCallback 418 * @param callback {Function|Object} the callback to execute 419 * @param params {Array} params to be passed to the callback method 420 * @param error {Boolean} whether an error occurred 421 * @param scope {Object} the scope from which to execute the callback 422 * (deprecated - use an object literal callback) 423 * @static 424 */ 425 issueCallback : function (callback,params,error,scope) { 426 if (lang.isFunction(callback)) { 427 callback.apply(scope, params); 428 } else if (lang.isObject(callback)) { 429 scope = callback.scope || scope || window; 430 var callbackFunc = callback.success; 431 if (error) { 432 callbackFunc = callback.failure; 433 } 434 if (callbackFunc) { 435 callbackFunc.apply(scope, params.concat([callback.argument])); 436 } 437 } 438 }, 439 440 /** 441 * Converts data to type String. 442 * 443 * @method DataSourceBase.parseString 444 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse. 445 * The special values null and undefined will return null. 446 * @return {String} A string, or null. 447 * @static 448 */ 449 parseString : function(oData) { 450 // Special case null and undefined 451 if(!lang.isValue(oData)) { 452 return null; 453 } 454 455 //Convert to string 456 var string = oData + ""; 457 458 // Validate 459 if(lang.isString(string)) { 460 return string; 461 } 462 else { 463 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type String", "warn", this.toString()); 464 return null; 465 } 466 }, 467 468 /** 469 * Converts data to type Number. 470 * 471 * @method DataSourceBase.parseNumber 472 * @param oData {String | Number | Boolean} Data to convert. Note, the following 473 * values return as null: null, undefined, NaN, "". 474 * @return {Number} A number, or null. 475 * @static 476 */ 477 parseNumber : function(oData) { 478 if(!lang.isValue(oData) || (oData === "")) { 479 return null; 480 } 481 482 //Convert to number 483 var number = oData * 1; 484 485 // Validate 486 if(lang.isNumber(number)) { 487 return number; 488 } 489 else { 490 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Number", "warn", this.toString()); 491 return null; 492 } 493 }, 494 // Backward compatibility 495 convertNumber : function(oData) { 496 YAHOO.log("The method YAHOO.util.DataSourceBase.convertNumber() has been" + 497 " deprecated in favor of YAHOO.util.DataSourceBase.parseNumber()", "warn", 498 this.toString()); 499 return DS.parseNumber(oData); 500 }, 501 502 /** 503 * Converts data to type Date. 504 * 505 * @method DataSourceBase.parseDate 506 * @param oData {Date | String | Number} Data to convert. 507 * @return {Date} A Date instance. 508 * @static 509 */ 510 parseDate : function(oData) { 511 var date = null; 512 513 //Convert to date 514 if(lang.isValue(oData) && !(oData instanceof Date)) { 515 date = new Date(oData); 516 } 517 else { 518 return oData; 519 } 520 521 // Validate 522 if(date instanceof Date) { 523 return date; 524 } 525 else { 526 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Date", "warn", this.toString()); 527 return null; 528 } 529 }, 530 // Backward compatibility 531 convertDate : function(oData) { 532 YAHOO.log("The method YAHOO.util.DataSourceBase.convertDate() has been" + 533 " deprecated in favor of YAHOO.util.DataSourceBase.parseDate()", "warn", 534 this.toString()); 535 return DS.parseDate(oData); 536 } 537 538 }); 539 540 // Done in separate step so referenced functions are defined. 541 /** 542 * Data parsing functions. 543 * @property DataSource.Parser 544 * @type Object 545 * @static 546 */ 547 DS.Parser = { 548 string : DS.parseString, 549 number : DS.parseNumber, 550 date : DS.parseDate 551 }; 552 553 // Prototype properties and methods 554 DS.prototype = { 555 556 ///////////////////////////////////////////////////////////////////////////// 557 // 558 // DataSourceBase private properties 559 // 560 ///////////////////////////////////////////////////////////////////////////// 561 562 /** 563 * Name of DataSource instance. 564 * 565 * @property _sName 566 * @type String 567 * @private 568 */ 569 _sName : null, 570 571 /** 572 * Local cache of data result object literals indexed chronologically. 573 * 574 * @property _aCache 575 * @type Object[] 576 * @private 577 */ 578 _aCache : null, 579 580 /** 581 * Local queue of request connections, enabled if queue needs to be managed. 582 * 583 * @property _oQueue 584 * @type Object 585 * @private 586 */ 587 _oQueue : null, 588 589 /** 590 * Array of polling interval IDs that have been enabled, needed to clear all intervals. 591 * 592 * @property _aIntervals 593 * @type Array 594 * @private 595 */ 596 _aIntervals : null, 597 598 ///////////////////////////////////////////////////////////////////////////// 599 // 600 // DataSourceBase public properties 601 // 602 ///////////////////////////////////////////////////////////////////////////// 603 604 /** 605 * Max size of the local cache. Set to 0 to turn off caching. Caching is 606 * useful to reduce the number of server connections. Recommended only for data 607 * sources that return comprehensive results for queries or when stale data is 608 * not an issue. 609 * 610 * @property maxCacheEntries 611 * @type Number 612 * @default 0 613 */ 614 maxCacheEntries : 0, 615 616 /** 617 * Pointer to live database. 618 * 619 * @property liveData 620 * @type Object 621 */ 622 liveData : null, 623 624 /** 625 * Where the live data is held: 626 * 627 * <dl> 628 * <dt>TYPE_UNKNOWN</dt> 629 * <dt>TYPE_LOCAL</dt> 630 * <dt>TYPE_XHR</dt> 631 * <dt>TYPE_SCRIPTNODE</dt> 632 * <dt>TYPE_JSFUNCTION</dt> 633 * </dl> 634 * 635 * @property dataType 636 * @type Number 637 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN 638 * 639 */ 640 dataType : DS.TYPE_UNKNOWN, 641 642 /** 643 * Format of response: 644 * 645 * <dl> 646 * <dt>TYPE_UNKNOWN</dt> 647 * <dt>TYPE_JSARRAY</dt> 648 * <dt>TYPE_JSON</dt> 649 * <dt>TYPE_XML</dt> 650 * <dt>TYPE_TEXT</dt> 651 * <dt>TYPE_HTMLTABLE</dt> 652 * </dl> 653 * 654 * @property responseType 655 * @type Number 656 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN 657 */ 658 responseType : DS.TYPE_UNKNOWN, 659 660 /** 661 * Response schema object literal takes a combination of the following properties: 662 * 663 * <dl> 664 * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd> 665 * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd> 666 * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd> 667 * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd> 668 * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals 669 * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd> 670 * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd> 671 * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd> 672 * </dl> 673 * 674 * @property responseSchema 675 * @type Object 676 */ 677 responseSchema : null, 678 679 /** 680 * Additional arguments passed to the JSON parse routine. The JSON string 681 * is the assumed first argument (where applicable). This property is not 682 * set by default, but the parse methods will use it if present. 683 * 684 * @property parseJSONArgs 685 * @type {MIXED|Array} If an Array, contents are used as individual arguments. 686 * Otherwise, value is used as an additional argument. 687 */ 688 // property intentionally undefined 689 690 /** 691 * When working with XML data, setting this property to true enables support for 692 * XPath-syntaxed locators in schema definitions. 693 * 694 * @property useXPath 695 * @type Boolean 696 * @default false 697 */ 698 useXPath : false, 699 700 /** 701 * Clones entries before adding to cache. 702 * 703 * @property cloneBeforeCaching 704 * @type Boolean 705 * @default false 706 */ 707 cloneBeforeCaching : false, 708 709 ///////////////////////////////////////////////////////////////////////////// 710 // 711 // DataSourceBase public methods 712 // 713 ///////////////////////////////////////////////////////////////////////////// 714 715 /** 716 * Public accessor to the unique name of the DataSource instance. 717 * 718 * @method toString 719 * @return {String} Unique name of the DataSource instance. 720 */ 721 toString : function() { 722 return this._sName; 723 }, 724 725 /** 726 * Overridable method passes request to cache and returns cached response if any, 727 * refreshing the hit in the cache as the newest item. Returns null if there is 728 * no cache hit. 729 * 730 * @method getCachedResponse 731 * @param oRequest {Object} Request object. 732 * @param oCallback {Object} Callback object. 733 * @param oCaller {Object} (deprecated) Use callback object. 734 * @return {Object} Cached response object or null. 735 */ 736 getCachedResponse : function(oRequest, oCallback, oCaller) { 737 var aCache = this._aCache; 738 739 // If cache is enabled... 740 if(this.maxCacheEntries > 0) { 741 // Initialize local cache 742 if(!aCache) { 743 this._aCache = []; 744 YAHOO.log("Cache initialized", "info", this.toString()); 745 } 746 // Look in local cache 747 else { 748 var nCacheLength = aCache.length; 749 if(nCacheLength > 0) { 750 var oResponse = null; 751 this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller}); 752 753 // Loop through each cached element 754 for(var i = nCacheLength-1; i >= 0; i--) { 755 var oCacheElem = aCache[i]; 756 757 // Defer cache hit logic to a public overridable method 758 if(this.isCacheHit(oRequest,oCacheElem.request)) { 759 // The cache returned a hit! 760 // Grab the cached response 761 oResponse = oCacheElem.response; 762 this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller}); 763 764 // Refresh the position of the cache hit 765 if(i < nCacheLength-1) { 766 // Remove element from its original location 767 aCache.splice(i,1); 768 // Add as newest 769 this.addToCache(oRequest, oResponse); 770 YAHOO.log("Refreshed cache position of the response for \"" + oRequest + "\"", "info", this.toString()); 771 } 772 773 // Add a cache flag 774 oResponse.cached = true; 775 break; 776 } 777 } 778 YAHOO.log("The cached response for \"" + lang.dump(oRequest) + 779 "\" is " + lang.dump(oResponse), "info", this.toString()); 780 return oResponse; 781 } 782 } 783 } 784 else if(aCache) { 785 this._aCache = null; 786 YAHOO.log("Cache destroyed", "info", this.toString()); 787 } 788 return null; 789 }, 790 791 /** 792 * Default overridable method matches given request to given cached request. 793 * Returns true if is a hit, returns false otherwise. Implementers should 794 * override this method to customize the cache-matching algorithm. 795 * 796 * @method isCacheHit 797 * @param oRequest {Object} Request object. 798 * @param oCachedRequest {Object} Cached request object. 799 * @return {Boolean} True if given request matches cached request, false otherwise. 800 */ 801 isCacheHit : function(oRequest, oCachedRequest) { 802 return (oRequest === oCachedRequest); 803 }, 804 805 /** 806 * Adds a new item to the cache. If cache is full, evicts the stalest item 807 * before adding the new item. 808 * 809 * @method addToCache 810 * @param oRequest {Object} Request object. 811 * @param oResponse {Object} Response object to cache. 812 */ 813 addToCache : function(oRequest, oResponse) { 814 var aCache = this._aCache; 815 if(!aCache) { 816 return; 817 } 818 819 // If the cache is full, make room by removing stalest element (index=0) 820 while(aCache.length >= this.maxCacheEntries) { 821 aCache.shift(); 822 } 823 824 // Add to cache in the newest position, at the end of the array 825 oResponse = (this.cloneBeforeCaching) ? DS._cloneObject(oResponse) : oResponse; 826 var oCacheElem = {request:oRequest,response:oResponse}; 827 aCache[aCache.length] = oCacheElem; 828 this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse}); 829 YAHOO.log("Cached the response for \"" + oRequest + "\"", "info", this.toString()); 830 }, 831 832 /** 833 * Flushes cache. 834 * 835 * @method flushCache 836 */ 837 flushCache : function() { 838 if(this._aCache) { 839 this._aCache = []; 840 this.fireEvent("cacheFlushEvent"); 841 YAHOO.log("Flushed the cache", "info", this.toString()); 842 } 843 }, 844 845 /** 846 * Sets up a polling mechanism to send requests at set intervals and forward 847 * responses to given callback. 848 * 849 * @method setInterval 850 * @param nMsec {Number} Length of interval in milliseconds. 851 * @param oRequest {Object} Request object. 852 * @param oCallback {Function} Handler function to receive the response. 853 * @param oCaller {Object} (deprecated) Use oCallback.scope. 854 * @return {Number} Interval ID. 855 */ 856 setInterval : function(nMsec, oRequest, oCallback, oCaller) { 857 if(lang.isNumber(nMsec) && (nMsec >= 0)) { 858 YAHOO.log("Enabling polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString()); 859 var oSelf = this; 860 var nId = setInterval(function() { 861 oSelf.makeConnection(oRequest, oCallback, oCaller); 862 }, nMsec); 863 this._aIntervals.push(nId); 864 return nId; 865 } 866 else { 867 YAHOO.log("Could not enable polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString()); 868 } 869 }, 870 871 /** 872 * Disables polling mechanism associated with the given interval ID. Does not 873 * affect transactions that are in progress. 874 * 875 * @method clearInterval 876 * @param nId {Number} Interval ID. 877 */ 878 clearInterval : function(nId) { 879 // Remove from tracker if there 880 var tracker = this._aIntervals || []; 881 for(var i=tracker.length-1; i>-1; i--) { 882 if(tracker[i] === nId) { 883 tracker.splice(i,1); 884 clearInterval(nId); 885 } 886 } 887 }, 888 889 /** 890 * Disables all known polling intervals. Does not affect transactions that are 891 * in progress. 892 * 893 * @method clearAllIntervals 894 */ 895 clearAllIntervals : function() { 896 var tracker = this._aIntervals || []; 897 for(var i=tracker.length-1; i>-1; i--) { 898 clearInterval(tracker[i]); 899 } 900 tracker = []; 901 }, 902 903 /** 904 * First looks for cached response, then sends request to live data. The 905 * following arguments are passed to the callback function: 906 * <dl> 907 * <dt><code>oRequest</code></dt> 908 * <dd>The same value that was passed in as the first argument to sendRequest.</dd> 909 * <dt><code>oParsedResponse</code></dt> 910 * <dd>An object literal containing the following properties: 911 * <dl> 912 * <dt><code>tId</code></dt> 913 * <dd>Unique transaction ID number.</dd> 914 * <dt><code>results</code></dt> 915 * <dd>Schema-parsed data results.</dd> 916 * <dt><code>error</code></dt> 917 * <dd>True in cases of data error.</dd> 918 * <dt><code>cached</code></dt> 919 * <dd>True when response is returned from DataSource cache.</dd> 920 * <dt><code>meta</code></dt> 921 * <dd>Schema-parsed meta data.</dd> 922 * </dl> 923 * <dt><code>oPayload</code></dt> 924 * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd> 925 * </dl> 926 * 927 * @method sendRequest 928 * @param oRequest {Object} Request object. 929 * @param oCallback {Object} An object literal with the following properties: 930 * <dl> 931 * <dt><code>success</code></dt> 932 * <dd>The function to call when the data is ready.</dd> 933 * <dt><code>failure</code></dt> 934 * <dd>The function to call upon a response failure condition.</dd> 935 * <dt><code>scope</code></dt> 936 * <dd>The object to serve as the scope for the success and failure handlers.</dd> 937 * <dt><code>argument</code></dt> 938 * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd> 939 * </dl> 940 * @param oCaller {Object} (deprecated) Use oCallback.scope. 941 * @return {Number} Transaction ID, or null if response found in cache. 942 */ 943 sendRequest : function(oRequest, oCallback, oCaller) { 944 // First look in cache 945 var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller); 946 if(oCachedResponse) { 947 DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller); 948 return null; 949 } 950 951 952 // Not in cache, so forward request to live data 953 YAHOO.log("Making connection to live data for \"" + oRequest + "\"", "info", this.toString()); 954 return this.makeConnection(oRequest, oCallback, oCaller); 955 }, 956 957 /** 958 * Overridable default method generates a unique transaction ID and passes 959 * the live data reference directly to the handleResponse function. This 960 * method should be implemented by subclasses to achieve more complex behavior 961 * or to access remote data. 962 * 963 * @method makeConnection 964 * @param oRequest {Object} Request object. 965 * @param oCallback {Object} Callback object literal. 966 * @param oCaller {Object} (deprecated) Use oCallback.scope. 967 * @return {Number} Transaction ID. 968 */ 969 makeConnection : function(oRequest, oCallback, oCaller) { 970 var tId = DS._nTransactionId++; 971 this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller}); 972 973 /* accounts for the following cases: 974 YAHOO.util.DataSourceBase.TYPE_UNKNOWN 975 YAHOO.util.DataSourceBase.TYPE_JSARRAY 976 YAHOO.util.DataSourceBase.TYPE_JSON 977 YAHOO.util.DataSourceBase.TYPE_HTMLTABLE 978 YAHOO.util.DataSourceBase.TYPE_XML 979 YAHOO.util.DataSourceBase.TYPE_TEXT 980 */ 981 var oRawResponse = this.liveData; 982 983 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); 984 return tId; 985 }, 986 987 /** 988 * Receives raw data response and type converts to XML, JSON, etc as necessary. 989 * Forwards oFullResponse to appropriate parsing function to get turned into 990 * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to 991 * the cache when appropriate before calling issueCallback(). 992 * 993 * The oParsedResponse object literal has the following properties: 994 * <dl> 995 * <dd><dt>tId {Number}</dt> Unique transaction ID</dd> 996 * <dd><dt>results {Array}</dt> Array of parsed data results</dd> 997 * <dd><dt>meta {Object}</dt> Object literal of meta values</dd> 998 * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd> 999 * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd> 1000 * </dl> 1001 * 1002 * @method handleResponse 1003 * @param oRequest {Object} Request object 1004 * @param oRawResponse {Object} The raw response from the live database. 1005 * @param oCallback {Object} Callback object literal. 1006 * @param oCaller {Object} (deprecated) Use oCallback.scope. 1007 * @param tId {Number} Transaction ID. 1008 */ 1009 handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) { 1010 this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse, 1011 callback:oCallback, caller:oCaller}); 1012 YAHOO.log("Received live data response for \"" + oRequest + "\"", "info", this.toString()); 1013 var xhr = (this.dataType == DS.TYPE_XHR) ? true : false; 1014 var oParsedResponse = null; 1015 var oFullResponse = oRawResponse; 1016 1017 // Try to sniff data type if it has not been defined 1018 if(this.responseType === DS.TYPE_UNKNOWN) { 1019 var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null; 1020 if(ctype) { 1021 // xml 1022 if(ctype.indexOf("text/xml") > -1) { 1023 this.responseType = DS.TYPE_XML; 1024 } 1025 else if(ctype.indexOf("application/json") > -1) { // json 1026 this.responseType = DS.TYPE_JSON; 1027 } 1028 else if(ctype.indexOf("text/plain") > -1) { // text 1029 this.responseType = DS.TYPE_TEXT; 1030 } 1031 } 1032 else { 1033 if(YAHOO.lang.isArray(oRawResponse)) { // array 1034 this.responseType = DS.TYPE_JSARRAY; 1035 } 1036 // xml 1037 else if(oRawResponse && oRawResponse.nodeType && (oRawResponse.nodeType === 9 || oRawResponse.nodeType === 1 || oRawResponse.nodeType === 11)) { 1038 this.responseType = DS.TYPE_XML; 1039 } 1040 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table 1041 this.responseType = DS.TYPE_HTMLTABLE; 1042 } 1043 else if(YAHOO.lang.isObject(oRawResponse)) { // json 1044 this.responseType = DS.TYPE_JSON; 1045 } 1046 else if(YAHOO.lang.isString(oRawResponse)) { // text 1047 this.responseType = DS.TYPE_TEXT; 1048 } 1049 } 1050 } 1051 1052 switch(this.responseType) { 1053 case DS.TYPE_JSARRAY: 1054 if(xhr && oRawResponse && oRawResponse.responseText) { 1055 oFullResponse = oRawResponse.responseText; 1056 } 1057 try { 1058 // Convert to JS array if it's a string 1059 if(lang.isString(oFullResponse)) { 1060 var parseArgs = [oFullResponse].concat(this.parseJSONArgs); 1061 // Check for YUI JSON Util 1062 if(lang.JSON) { 1063 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); 1064 } 1065 // Look for JSON parsers using an API similar to json2.js 1066 else if(window.JSON && JSON.parse) { 1067 oFullResponse = JSON.parse.apply(JSON,parseArgs); 1068 } 1069 // Look for JSON parsers using an API similar to json.js 1070 else if(oFullResponse.parseJSON) { 1071 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); 1072 } 1073 // No JSON lib found so parse the string 1074 else { 1075 // Trim leading spaces 1076 while (oFullResponse.length > 0 && 1077 (oFullResponse.charAt(0) != "{") && 1078 (oFullResponse.charAt(0) != "[")) { 1079 oFullResponse = oFullResponse.substring(1, oFullResponse.length); 1080 } 1081 1082 if(oFullResponse.length > 0) { 1083 // Strip extraneous stuff at the end 1084 var arrayEnd = 1085 Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); 1086 oFullResponse = oFullResponse.substring(0,arrayEnd+1); 1087 1088 // Turn the string into an object literal... 1089 // ...eval is necessary here 1090 oFullResponse = eval("(" + oFullResponse + ")"); 1091 1092 } 1093 } 1094 } 1095 } 1096 catch(e1) { 1097 } 1098 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1099 oParsedResponse = this.parseArrayData(oRequest, oFullResponse); 1100 break; 1101 case DS.TYPE_JSON: 1102 if(xhr && oRawResponse && oRawResponse.responseText) { 1103 oFullResponse = oRawResponse.responseText; 1104 } 1105 try { 1106 // Convert to JSON object if it's a string 1107 if(lang.isString(oFullResponse)) { 1108 var parseArgs = [oFullResponse].concat(this.parseJSONArgs); 1109 // Check for YUI JSON Util 1110 if(lang.JSON) { 1111 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); 1112 } 1113 // Look for JSON parsers using an API similar to json2.js 1114 else if(window.JSON && JSON.parse) { 1115 oFullResponse = JSON.parse.apply(JSON,parseArgs); 1116 } 1117 // Look for JSON parsers using an API similar to json.js 1118 else if(oFullResponse.parseJSON) { 1119 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); 1120 } 1121 // No JSON lib found so parse the string 1122 else { 1123 // Trim leading spaces 1124 while (oFullResponse.length > 0 && 1125 (oFullResponse.charAt(0) != "{") && 1126 (oFullResponse.charAt(0) != "[")) { 1127 oFullResponse = oFullResponse.substring(1, oFullResponse.length); 1128 } 1129 1130 if(oFullResponse.length > 0) { 1131 // Strip extraneous stuff at the end 1132 var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); 1133 oFullResponse = oFullResponse.substring(0,objEnd+1); 1134 1135 // Turn the string into an object literal... 1136 // ...eval is necessary here 1137 oFullResponse = eval("(" + oFullResponse + ")"); 1138 1139 } 1140 } 1141 } 1142 } 1143 catch(e) { 1144 } 1145 1146 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1147 oParsedResponse = this.parseJSONData(oRequest, oFullResponse); 1148 break; 1149 case DS.TYPE_HTMLTABLE: 1150 if(xhr && oRawResponse.responseText) { 1151 var el = document.createElement('div'); 1152 el.innerHTML = oRawResponse.responseText; 1153 oFullResponse = el.getElementsByTagName('table')[0]; 1154 } 1155 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1156 oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse); 1157 break; 1158 case DS.TYPE_XML: 1159 if(xhr && oRawResponse.responseXML) { 1160 oFullResponse = oRawResponse.responseXML; 1161 } 1162 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1163 oParsedResponse = this.parseXMLData(oRequest, oFullResponse); 1164 break; 1165 case DS.TYPE_TEXT: 1166 if(xhr && lang.isString(oRawResponse.responseText)) { 1167 oFullResponse = oRawResponse.responseText; 1168 } 1169 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1170 oParsedResponse = this.parseTextData(oRequest, oFullResponse); 1171 break; 1172 default: 1173 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); 1174 oParsedResponse = this.parseData(oRequest, oFullResponse); 1175 break; 1176 } 1177 1178 1179 // Clean up for consistent signature 1180 oParsedResponse = oParsedResponse || {}; 1181 if(!oParsedResponse.results) { 1182 oParsedResponse.results = []; 1183 } 1184 if(!oParsedResponse.meta) { 1185 oParsedResponse.meta = {}; 1186 } 1187 1188 // Success 1189 if(!oParsedResponse.error) { 1190 // Last chance to touch the raw response or the parsed response 1191 oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback); 1192 this.fireEvent("responseParseEvent", {request:oRequest, 1193 response:oParsedResponse, callback:oCallback, caller:oCaller}); 1194 // Cache the response 1195 this.addToCache(oRequest, oParsedResponse); 1196 } 1197 // Error 1198 else { 1199 // Be sure the error flag is on 1200 oParsedResponse.error = true; 1201 this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback, 1202 caller:oCaller, message:DS.ERROR_DATANULL}); 1203 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString()); 1204 } 1205 1206 // Send the response back to the caller 1207 oParsedResponse.tId = tId; 1208 DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller); 1209 }, 1210 1211 /** 1212 * Overridable method gives implementers access to the original full response 1213 * before the data gets parsed. Implementers should take care not to return an 1214 * unparsable or otherwise invalid response. 1215 * 1216 * @method doBeforeParseData 1217 * @param oRequest {Object} Request object. 1218 * @param oFullResponse {Object} The full response from the live database. 1219 * @param oCallback {Object} The callback object. 1220 * @return {Object} Full response for parsing. 1221 1222 */ 1223 doBeforeParseData : function(oRequest, oFullResponse, oCallback) { 1224 return oFullResponse; 1225 }, 1226 1227 /** 1228 * Overridable method gives implementers access to the original full response and 1229 * the parsed response (parsed against the given schema) before the data 1230 * is added to the cache (if applicable) and then sent back to callback function. 1231 * This is your chance to access the raw response and/or populate the parsed 1232 * response with any custom data. 1233 * 1234 * @method doBeforeCallback 1235 * @param oRequest {Object} Request object. 1236 * @param oFullResponse {Object} The full response from the live database. 1237 * @param oParsedResponse {Object} The parsed response to return to calling object. 1238 * @param oCallback {Object} The callback object. 1239 * @return {Object} Parsed response object. 1240 */ 1241 doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) { 1242 return oParsedResponse; 1243 }, 1244 1245 /** 1246 * Overridable method parses data of generic RESPONSE_TYPE into a response object. 1247 * 1248 * @method parseData 1249 * @param oRequest {Object} Request object. 1250 * @param oFullResponse {Object} The full Array from the live database. 1251 * @return {Object} Parsed response object with the following properties:<br> 1252 * - results {Array} Array of parsed data results<br> 1253 * - meta {Object} Object literal of meta values<br> 1254 * - error {Boolean} (optional) True if there was an error<br> 1255 */ 1256 parseData : function(oRequest, oFullResponse) { 1257 if(lang.isValue(oFullResponse)) { 1258 var oParsedResponse = {results:oFullResponse,meta:{}}; 1259 YAHOO.log("Parsed generic data is " + 1260 lang.dump(oParsedResponse), "info", this.toString()); 1261 return oParsedResponse; 1262 1263 } 1264 YAHOO.log("Generic data could not be parsed: " + lang.dump(oFullResponse), 1265 "error", this.toString()); 1266 return null; 1267 }, 1268 1269 /** 1270 * Overridable method parses Array data into a response object. 1271 * 1272 * @method parseArrayData 1273 * @param oRequest {Object} Request object. 1274 * @param oFullResponse {Object} The full Array from the live database. 1275 * @return {Object} Parsed response object with the following properties:<br> 1276 * - results (Array) Array of parsed data results<br> 1277 * - error (Boolean) True if there was an error 1278 */ 1279 parseArrayData : function(oRequest, oFullResponse) { 1280 if(lang.isArray(oFullResponse)) { 1281 var results = [], 1282 i, j, 1283 rec, field, data; 1284 1285 // Parse for fields 1286 if(lang.isArray(this.responseSchema.fields)) { 1287 var fields = this.responseSchema.fields; 1288 for (i = fields.length - 1; i >= 0; --i) { 1289 if (typeof fields[i] !== 'object') { 1290 fields[i] = { key : fields[i] }; 1291 } 1292 } 1293 1294 var parsers = {}, p; 1295 for (i = fields.length - 1; i >= 0; --i) { 1296 p = (typeof fields[i].parser === 'function' ? 1297 fields[i].parser : 1298 DS.Parser[fields[i].parser+'']) || fields[i].converter; 1299 if (p) { 1300 parsers[fields[i].key] = p; 1301 } 1302 } 1303 1304 var arrType = lang.isArray(oFullResponse[0]); 1305 for(i=oFullResponse.length-1; i>-1; i--) { 1306 var oResult = {}; 1307 rec = oFullResponse[i]; 1308 if (typeof rec === 'object') { 1309 for(j=fields.length-1; j>-1; j--) { 1310 field = fields[j]; 1311 data = arrType ? rec[j] : rec[field.key]; 1312 1313 if (parsers[field.key]) { 1314 data = parsers[field.key].call(this,data); 1315 } 1316 1317 // Safety measure 1318 if(data === undefined) { 1319 data = null; 1320 } 1321 1322 oResult[field.key] = data; 1323 } 1324 } 1325 else if (lang.isString(rec)) { 1326 for(j=fields.length-1; j>-1; j--) { 1327 field = fields[j]; 1328 data = rec; 1329 1330 if (parsers[field.key]) { 1331 data = parsers[field.key].call(this,data); 1332 } 1333 1334 // Safety measure 1335 if(data === undefined) { 1336 data = null; 1337 } 1338 1339 oResult[field.key] = data; 1340 } 1341 } 1342 results[i] = oResult; 1343 } 1344 } 1345 // Return entire data set 1346 else { 1347 results = oFullResponse; 1348 } 1349 var oParsedResponse = {results:results}; 1350 YAHOO.log("Parsed array data is " + 1351 lang.dump(oParsedResponse), "info", this.toString()); 1352 return oParsedResponse; 1353 1354 } 1355 YAHOO.log("Array data could not be parsed: " + lang.dump(oFullResponse), 1356 "error", this.toString()); 1357 return null; 1358 }, 1359 1360 /** 1361 * Overridable method parses plain text data into a response object. 1362 * 1363 * @method parseTextData 1364 * @param oRequest {Object} Request object. 1365 * @param oFullResponse {Object} The full text response from the live database. 1366 * @return {Object} Parsed response object with the following properties:<br> 1367 * - results (Array) Array of parsed data results<br> 1368 * - error (Boolean) True if there was an error 1369 */ 1370 parseTextData : function(oRequest, oFullResponse) { 1371 if(lang.isString(oFullResponse)) { 1372 if(lang.isString(this.responseSchema.recordDelim) && 1373 lang.isString(this.responseSchema.fieldDelim)) { 1374 var oParsedResponse = {results:[]}; 1375 var recDelim = this.responseSchema.recordDelim; 1376 var fieldDelim = this.responseSchema.fieldDelim; 1377 if(oFullResponse.length > 0) { 1378 // Delete the last line delimiter at the end of the data if it exists 1379 var newLength = oFullResponse.length-recDelim.length; 1380 if(oFullResponse.substr(newLength) == recDelim) { 1381 oFullResponse = oFullResponse.substr(0, newLength); 1382 } 1383 if(oFullResponse.length > 0) { 1384 // Split along record delimiter to get an array of strings 1385 var recordsarray = oFullResponse.split(recDelim); 1386 // Cycle through each record 1387 for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) { 1388 var bError = false, 1389 sRecord = recordsarray[i]; 1390 if (lang.isString(sRecord) && (sRecord.length > 0)) { 1391 // Split each record along field delimiter to get data 1392 var fielddataarray = recordsarray[i].split(fieldDelim); 1393 var oResult = {}; 1394 1395 // Filter for fields data 1396 if(lang.isArray(this.responseSchema.fields)) { 1397 var fields = this.responseSchema.fields; 1398 for(var j=fields.length-1; j>-1; j--) { 1399 try { 1400 // Remove quotation marks from edges, if applicable 1401 var data = fielddataarray[j]; 1402 if (lang.isString(data)) { 1403 if(data.charAt(0) == "\"") { 1404 data = data.substr(1); 1405 } 1406 if(data.charAt(data.length-1) == "\"") { 1407 data = data.substr(0,data.length-1); 1408 } 1409 var field = fields[j]; 1410 var key = (lang.isValue(field.key)) ? field.key : field; 1411 // Backward compatibility 1412 if(!field.parser && field.converter) { 1413 field.parser = field.converter; 1414 YAHOO.log("The field property converter has been deprecated" + 1415 " in favor of parser", "warn", this.toString()); 1416 } 1417 var parser = (typeof field.parser === 'function') ? 1418 field.parser : 1419 DS.Parser[field.parser+'']; 1420 if(parser) { 1421 data = parser.call(this, data); 1422 } 1423 // Safety measure 1424 if(data === undefined) { 1425 data = null; 1426 } 1427 oResult[key] = data; 1428 } 1429 else { 1430 bError = true; 1431 } 1432 } 1433 catch(e) { 1434 bError = true; 1435 } 1436 } 1437 } 1438 // No fields defined so pass along all data as an array 1439 else { 1440 oResult = fielddataarray; 1441 } 1442 if(!bError) { 1443 oParsedResponse.results[recIdx++] = oResult; 1444 } 1445 } 1446 } 1447 } 1448 } 1449 YAHOO.log("Parsed text data is " + 1450 lang.dump(oParsedResponse), "info", this.toString()); 1451 return oParsedResponse; 1452 } 1453 } 1454 YAHOO.log("Text data could not be parsed: " + lang.dump(oFullResponse), 1455 "error", this.toString()); 1456 return null; 1457 1458 }, 1459 1460 /** 1461 * Overridable method parses XML data for one result into an object literal. 1462 * 1463 * @method parseXMLResult 1464 * @param result {XML} XML for one result. 1465 * @return {Object} Object literal of data for one result. 1466 */ 1467 parseXMLResult : function(result) { 1468 var oResult = {}, 1469 schema = this.responseSchema; 1470 1471 try { 1472 // Loop through each data field in each result using the schema 1473 for(var m = schema.fields.length-1; m >= 0 ; m--) { 1474 var field = schema.fields[m]; 1475 var key = (lang.isValue(field.key)) ? field.key : field; 1476 var data = null; 1477 1478 if(this.useXPath) { 1479 data = YAHOO.util.DataSource._getLocationValue(field, result); 1480 } 1481 else { 1482 // Values may be held in an attribute... 1483 var xmlAttr = result.attributes.getNamedItem(key); 1484 if(xmlAttr) { 1485 data = xmlAttr.value; 1486 } 1487 // ...or in a node 1488 else { 1489 var xmlNode = result.getElementsByTagName(key); 1490 if(xmlNode && xmlNode.item(0)) { 1491 var item = xmlNode.item(0); 1492 // For IE, then DOM... 1493 data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null; 1494 // ...then fallback, but check for multiple child nodes 1495 if(!data) { 1496 var datapieces = []; 1497 for(var j=0, len=item.childNodes.length; j<len; j++) { 1498 if(item.childNodes[j].nodeValue) { 1499 datapieces[datapieces.length] = item.childNodes[j].nodeValue; 1500 } 1501 } 1502 if(datapieces.length > 0) { 1503 data = datapieces.join(""); 1504 } 1505 } 1506 } 1507 } 1508 } 1509 1510 1511 // Safety net 1512 if(data === null) { 1513 data = ""; 1514 } 1515 // Backward compatibility 1516 if(!field.parser && field.converter) { 1517 field.parser = field.converter; 1518 YAHOO.log("The field property converter has been deprecated" + 1519 " in favor of parser", "warn", this.toString()); 1520 } 1521 var parser = (typeof field.parser === 'function') ? 1522 field.parser : 1523 DS.Parser[field.parser+'']; 1524 if(parser) { 1525 data = parser.call(this, data); 1526 } 1527 // Safety measure 1528 if(data === undefined) { 1529 data = null; 1530 } 1531 oResult[key] = data; 1532 } 1533 } 1534 catch(e) { 1535 YAHOO.log("Error while parsing XML result: " + e.message); 1536 } 1537 1538 return oResult; 1539 }, 1540 1541 1542 1543 /** 1544 * Overridable method parses XML data into a response object. 1545 * 1546 * @method parseXMLData 1547 * @param oRequest {Object} Request object. 1548 * @param oFullResponse {Object} The full XML response from the live database. 1549 * @return {Object} Parsed response object with the following properties<br> 1550 * - results (Array) Array of parsed data results<br> 1551 * - error (Boolean) True if there was an error 1552 */ 1553 parseXMLData : function(oRequest, oFullResponse) { 1554 var bError = false, 1555 schema = this.responseSchema, 1556 oParsedResponse = {meta:{}}, 1557 xmlList = null, 1558 metaNode = schema.metaNode, 1559 metaLocators = schema.metaFields || {}, 1560 i,k,loc,v; 1561 1562 // In case oFullResponse is something funky 1563 try { 1564 // Pull any meta identified 1565 if(this.useXPath) { 1566 for (k in metaLocators) { 1567 oParsedResponse.meta[k] = YAHOO.util.DataSource._getLocationValue(metaLocators[k], oFullResponse); 1568 } 1569 } 1570 else { 1571 metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] : 1572 oFullResponse; 1573 1574 if (metaNode) { 1575 for (k in metaLocators) { 1576 if (lang.hasOwnProperty(metaLocators, k)) { 1577 loc = metaLocators[k]; 1578 // Look for a node 1579 v = metaNode.getElementsByTagName(loc)[0]; 1580 1581 if (v) { 1582 v = v.firstChild.nodeValue; 1583 } else { 1584 // Look for an attribute 1585 v = metaNode.attributes.getNamedItem(loc); 1586 if (v) { 1587 v = v.value; 1588 } 1589 } 1590 1591 if (lang.isValue(v)) { 1592 oParsedResponse.meta[k] = v; 1593 } 1594 } 1595 } 1596 } 1597 } 1598 1599 // For result data 1600 xmlList = (schema.resultNode) ? 1601 oFullResponse.getElementsByTagName(schema.resultNode) : 1602 null; 1603 } 1604 catch(e) { 1605 YAHOO.log("Error while parsing XML data: " + e.message); 1606 } 1607 if(!xmlList || !lang.isArray(schema.fields)) { 1608 bError = true; 1609 } 1610 // Loop through each result 1611 else { 1612 oParsedResponse.results = []; 1613 for(i = xmlList.length-1; i >= 0 ; --i) { 1614 var oResult = this.parseXMLResult(xmlList.item(i)); 1615 // Capture each array of values into an array of results 1616 oParsedResponse.results[i] = oResult; 1617 } 1618 } 1619 if(bError) { 1620 YAHOO.log("XML data could not be parsed: " + 1621 lang.dump(oFullResponse), "error", this.toString()); 1622 oParsedResponse.error = true; 1623 } 1624 else { 1625 YAHOO.log("Parsed XML data is " + 1626 lang.dump(oParsedResponse), "info", this.toString()); 1627 } 1628 return oParsedResponse; 1629 }, 1630 1631 /** 1632 * Overridable method parses JSON data into a response object. 1633 * 1634 * @method parseJSONData 1635 * @param oRequest {Object} Request object. 1636 * @param oFullResponse {Object} The full JSON from the live database. 1637 * @return {Object} Parsed response object with the following properties<br> 1638 * - results (Array) Array of parsed data results<br> 1639 * - error (Boolean) True if there was an error 1640 */ 1641 parseJSONData : function(oRequest, oFullResponse) { 1642 var oParsedResponse = {results:[],meta:{}}; 1643 1644 if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) { 1645 var schema = this.responseSchema, 1646 fields = schema.fields, 1647 resultsList = oFullResponse, 1648 results = [], 1649 metaFields = schema.metaFields || {}, 1650 fieldParsers = [], 1651 fieldPaths = [], 1652 simpleFields = [], 1653 bError = false, 1654 i,len,j,v,key,parser,path; 1655 1656 // Function to convert the schema's fields into walk paths 1657 var buildPath = function (needle) { 1658 var path = null, keys = [], i = 0; 1659 if (needle) { 1660 // Strip the ["string keys"] and [1] array indexes 1661 needle = needle. 1662 replace(/\[(['"])(.*?)\1\]/g, 1663 function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}). 1664 replace(/\[(\d+)\]/g, 1665 function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}). 1666 replace(/^\./,''); // remove leading dot 1667 1668 // If the cleaned needle contains invalid characters, the 1669 // path is invalid 1670 if (!/[^\w\.\$@]/.test(needle)) { 1671 path = needle.split('.'); 1672 for (i=path.length-1; i >= 0; --i) { 1673 if (path[i].charAt(0) === '@') { 1674 path[i] = keys[parseInt(path[i].substr(1),10)]; 1675 } 1676 } 1677 } 1678 else { 1679 YAHOO.log("Invalid locator: " + needle, "error", this.toString()); 1680 } 1681 } 1682 return path; 1683 }; 1684 1685 1686 // Function to walk a path and return the pot of gold 1687 var walkPath = function (path, origin) { 1688 var v=origin,i=0,len=path.length; 1689 for (;i<len && v;++i) { 1690 v = v[path[i]]; 1691 } 1692 return v; 1693 }; 1694 1695 // Parse the response 1696 // Step 1. Pull the resultsList from oFullResponse (default assumes 1697 // oFullResponse IS the resultsList) 1698 path = buildPath(schema.resultsList); 1699 if (path) { 1700 resultsList = walkPath(path, oFullResponse); 1701 if (resultsList === undefined) { 1702 bError = true; 1703 } 1704 } else { 1705 bError = true; 1706 } 1707 1708 if (!resultsList) { 1709 resultsList = []; 1710 } 1711 1712 if (!lang.isArray(resultsList)) { 1713 resultsList = [resultsList]; 1714 } 1715 1716 if (!bError) { 1717 // Step 2. Parse out field data if identified 1718 if(schema.fields) { 1719 var field; 1720 // Build the field parser map and location paths 1721 for (i=0, len=fields.length; i<len; i++) { 1722 field = fields[i]; 1723 key = field.key || field; 1724 parser = ((typeof field.parser === 'function') ? 1725 field.parser : 1726 DS.Parser[field.parser+'']) || field.converter; 1727 path = buildPath(key); 1728 1729 if (parser) { 1730 fieldParsers[fieldParsers.length] = {key:key,parser:parser}; 1731 } 1732 1733 if (path) { 1734 if (path.length > 1) { 1735 fieldPaths[fieldPaths.length] = {key:key,path:path}; 1736 } else { 1737 simpleFields[simpleFields.length] = {key:key,path:path[0]}; 1738 } 1739 } else { 1740 YAHOO.log("Invalid key syntax: " + key,"warn",this.toString()); 1741 } 1742 } 1743 1744 // Process the results, flattening the records and/or applying parsers if needed 1745 for (i = resultsList.length - 1; i >= 0; --i) { 1746 var r = resultsList[i], rec = {}; 1747 if(r) { 1748 for (j = simpleFields.length - 1; j >= 0; --j) { 1749 // Bug 1777850: data might be held in an array 1750 rec[simpleFields[j].key] = 1751 (r[simpleFields[j].path] !== undefined) ? 1752 r[simpleFields[j].path] : r[j]; 1753 } 1754 1755 for (j = fieldPaths.length - 1; j >= 0; --j) { 1756 rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r); 1757 } 1758 1759 for (j = fieldParsers.length - 1; j >= 0; --j) { 1760 var p = fieldParsers[j].key; 1761 rec[p] = fieldParsers[j].parser.call(this, rec[p]); 1762 if (rec[p] === undefined) { 1763 rec[p] = null; 1764 } 1765 } 1766 } 1767 results[i] = rec; 1768 } 1769 } 1770 else { 1771 results = resultsList; 1772 } 1773 1774 for (key in metaFields) { 1775 if (lang.hasOwnProperty(metaFields,key)) { 1776 path = buildPath(metaFields[key]); 1777 if (path) { 1778 v = walkPath(path, oFullResponse); 1779 oParsedResponse.meta[key] = v; 1780 } 1781 } 1782 } 1783 1784 } else { 1785 YAHOO.log("JSON data could not be parsed due to invalid responseSchema.resultsList or invalid response: " + 1786 lang.dump(oFullResponse), "error", this.toString()); 1787 1788 oParsedResponse.error = true; 1789 } 1790 1791 oParsedResponse.results = results; 1792 } 1793 else { 1794 YAHOO.log("JSON data could not be parsed: " + 1795 lang.dump(oFullResponse), "error", this.toString()); 1796 oParsedResponse.error = true; 1797 } 1798 1799 return oParsedResponse; 1800 }, 1801 1802 /** 1803 * Overridable method parses an HTML TABLE element reference into a response object. 1804 * Data is parsed out of TR elements from all TBODY elements. 1805 * 1806 * @method parseHTMLTableData 1807 * @param oRequest {Object} Request object. 1808 * @param oFullResponse {Object} The full HTML element reference from the live database. 1809 * @return {Object} Parsed response object with the following properties<br> 1810 * - results (Array) Array of parsed data results<br> 1811 * - error (Boolean) True if there was an error 1812 */ 1813 parseHTMLTableData : function(oRequest, oFullResponse) { 1814 var bError = false; 1815 var elTable = oFullResponse; 1816 var fields = this.responseSchema.fields; 1817 var oParsedResponse = {results:[]}; 1818 1819 if(lang.isArray(fields)) { 1820 // Iterate through each TBODY 1821 for(var i=0; i<elTable.tBodies.length; i++) { 1822 var elTbody = elTable.tBodies[i]; 1823 1824 // Iterate through each TR 1825 for(var j=elTbody.rows.length-1; j>-1; j--) { 1826 var elRow = elTbody.rows[j]; 1827 var oResult = {}; 1828 1829 for(var k=fields.length-1; k>-1; k--) { 1830 var field = fields[k]; 1831 var key = (lang.isValue(field.key)) ? field.key : field; 1832 var data = elRow.cells[k].innerHTML; 1833 1834 // Backward compatibility 1835 if(!field.parser && field.converter) { 1836 field.parser = field.converter; 1837 YAHOO.log("The field property converter has been deprecated" + 1838 " in favor of parser", "warn", this.toString()); 1839 } 1840 var parser = (typeof field.parser === 'function') ? 1841 field.parser : 1842 DS.Parser[field.parser+'']; 1843 if(parser) { 1844 data = parser.call(this, data); 1845 } 1846 // Safety measure 1847 if(data === undefined) { 1848 data = null; 1849 } 1850 oResult[key] = data; 1851 } 1852 oParsedResponse.results[j] = oResult; 1853 } 1854 } 1855 } 1856 else { 1857 bError = true; 1858 YAHOO.log("Invalid responseSchema.fields", "error", this.toString()); 1859 } 1860 1861 if(bError) { 1862 YAHOO.log("HTML TABLE data could not be parsed: " + 1863 lang.dump(oFullResponse), "error", this.toString()); 1864 oParsedResponse.error = true; 1865 } 1866 else { 1867 YAHOO.log("Parsed HTML TABLE data is " + 1868 lang.dump(oParsedResponse), "info", this.toString()); 1869 } 1870 return oParsedResponse; 1871 } 1872 1873 }; 1874 1875 // DataSourceBase uses EventProvider 1876 lang.augmentProto(DS, util.EventProvider); 1877 1878 1879 1880 /****************************************************************************/ 1881 /****************************************************************************/ 1882 /****************************************************************************/ 1883 1884 /** 1885 * LocalDataSource class for in-memory data structs including JavaScript arrays, 1886 * JavaScript object literals (JSON), XML documents, and HTML tables. 1887 * 1888 * @namespace YAHOO.util 1889 * @class YAHOO.util.LocalDataSource 1890 * @extends YAHOO.util.DataSourceBase 1891 * @constructor 1892 * @param oLiveData {HTMLElement} Pointer to live data. 1893 * @param oConfigs {object} (optional) Object literal of configuration values. 1894 */ 1895 util.LocalDataSource = function(oLiveData, oConfigs) { 1896 this.dataType = DS.TYPE_LOCAL; 1897 1898 if(oLiveData) { 1899 if(YAHOO.lang.isArray(oLiveData)) { // array 1900 this.responseType = DS.TYPE_JSARRAY; 1901 } 1902 // xml 1903 else if(oLiveData.nodeType && oLiveData.nodeType == 9) { 1904 this.responseType = DS.TYPE_XML; 1905 } 1906 else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table 1907 this.responseType = DS.TYPE_HTMLTABLE; 1908 oLiveData = oLiveData.cloneNode(true); 1909 } 1910 else if(YAHOO.lang.isString(oLiveData)) { // text 1911 this.responseType = DS.TYPE_TEXT; 1912 } 1913 else if(YAHOO.lang.isObject(oLiveData)) { // json 1914 this.responseType = DS.TYPE_JSON; 1915 } 1916 } 1917 else { 1918 oLiveData = []; 1919 this.responseType = DS.TYPE_JSARRAY; 1920 } 1921 1922 util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 1923 }; 1924 1925 // LocalDataSource extends DataSourceBase 1926 lang.extend(util.LocalDataSource, DS); 1927 1928 // Copy static members to LocalDataSource class 1929 lang.augmentObject(util.LocalDataSource, DS); 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 /****************************************************************************/ 1944 /****************************************************************************/ 1945 /****************************************************************************/ 1946 1947 /** 1948 * FunctionDataSource class for JavaScript functions. 1949 * 1950 * @namespace YAHOO.util 1951 * @class YAHOO.util.FunctionDataSource 1952 * @extends YAHOO.util.DataSourceBase 1953 * @constructor 1954 * @param oLiveData {HTMLElement} Pointer to live data. 1955 * @param oConfigs {object} (optional) Object literal of configuration values. 1956 */ 1957 util.FunctionDataSource = function(oLiveData, oConfigs) { 1958 this.dataType = DS.TYPE_JSFUNCTION; 1959 oLiveData = oLiveData || function() {}; 1960 1961 util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 1962 }; 1963 1964 // FunctionDataSource extends DataSourceBase 1965 lang.extend(util.FunctionDataSource, DS, { 1966 1967 ///////////////////////////////////////////////////////////////////////////// 1968 // 1969 // FunctionDataSource public properties 1970 // 1971 ///////////////////////////////////////////////////////////////////////////// 1972 1973 /** 1974 * Context in which to execute the function. By default, is the DataSource 1975 * instance itself. If set, the function will receive the DataSource instance 1976 * as an additional argument. 1977 * 1978 * @property scope 1979 * @type Object 1980 * @default null 1981 */ 1982 scope : null, 1983 1984 1985 ///////////////////////////////////////////////////////////////////////////// 1986 // 1987 // FunctionDataSource public methods 1988 // 1989 ///////////////////////////////////////////////////////////////////////////// 1990 1991 /** 1992 * Overriding method passes query to a function. The returned response is then 1993 * forwarded to the handleResponse function. 1994 * 1995 * @method makeConnection 1996 * @param oRequest {Object} Request object. 1997 * @param oCallback {Object} Callback object literal. 1998 * @param oCaller {Object} (deprecated) Use oCallback.scope. 1999 * @return {Number} Transaction ID. 2000 */ 2001 makeConnection : function(oRequest, oCallback, oCaller) { 2002 var tId = DS._nTransactionId++; 2003 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); 2004 2005 // Pass the request in as a parameter and 2006 // forward the return value to the handler 2007 2008 2009 var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this, oCallback) : this.liveData(oRequest, oCallback); 2010 2011 // Try to sniff data type if it has not been defined 2012 if(this.responseType === DS.TYPE_UNKNOWN) { 2013 if(YAHOO.lang.isArray(oRawResponse)) { // array 2014 this.responseType = DS.TYPE_JSARRAY; 2015 } 2016 // xml 2017 else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) { 2018 this.responseType = DS.TYPE_XML; 2019 } 2020 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table 2021 this.responseType = DS.TYPE_HTMLTABLE; 2022 } 2023 else if(YAHOO.lang.isObject(oRawResponse)) { // json 2024 this.responseType = DS.TYPE_JSON; 2025 } 2026 else if(YAHOO.lang.isString(oRawResponse)) { // text 2027 this.responseType = DS.TYPE_TEXT; 2028 } 2029 } 2030 2031 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); 2032 return tId; 2033 } 2034 2035 }); 2036 2037 // Copy static members to FunctionDataSource class 2038 lang.augmentObject(util.FunctionDataSource, DS); 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 /****************************************************************************/ 2053 /****************************************************************************/ 2054 /****************************************************************************/ 2055 2056 /** 2057 * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility. 2058 * 2059 * @namespace YAHOO.util 2060 * @class YAHOO.util.ScriptNodeDataSource 2061 * @extends YAHOO.util.DataSourceBase 2062 * @constructor 2063 * @param oLiveData {HTMLElement} Pointer to live data. 2064 * @param oConfigs {object} (optional) Object literal of configuration values. 2065 */ 2066 util.ScriptNodeDataSource = function(oLiveData, oConfigs) { 2067 this.dataType = DS.TYPE_SCRIPTNODE; 2068 oLiveData = oLiveData || ""; 2069 2070 util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 2071 }; 2072 2073 // ScriptNodeDataSource extends DataSourceBase 2074 lang.extend(util.ScriptNodeDataSource, DS, { 2075 2076 ///////////////////////////////////////////////////////////////////////////// 2077 // 2078 // ScriptNodeDataSource public properties 2079 // 2080 ///////////////////////////////////////////////////////////////////////////// 2081 2082 /** 2083 * Alias to YUI Get Utility, to allow implementers to use a custom class. 2084 * 2085 * @property getUtility 2086 * @type Object 2087 * @default YAHOO.util.Get 2088 */ 2089 getUtility : util.Get, 2090 2091 /** 2092 * Defines request/response management in the following manner: 2093 * <dl> 2094 * <!--<dt>queueRequests</dt> 2095 * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd> 2096 * <dt>cancelStaleRequests</dt> 2097 * <dd>If a request is already in progress, cancel it before sending the next request.</dd>--> 2098 * <dt>ignoreStaleResponses</dt> 2099 * <dd>Send all requests, but handle only the response for the most recently sent request.</dd> 2100 * <dt>allowAll</dt> 2101 * <dd>Send all requests and handle all responses.</dd> 2102 * </dl> 2103 * 2104 * @property asyncMode 2105 * @type String 2106 * @default "allowAll" 2107 */ 2108 asyncMode : "allowAll", 2109 2110 /** 2111 * Callback string parameter name sent to the remote script. By default, 2112 * requests are sent to 2113 * <URI>?<scriptCallbackParam>=callback 2114 * 2115 * @property scriptCallbackParam 2116 * @type String 2117 * @default "callback" 2118 */ 2119 scriptCallbackParam : "callback", 2120 2121 2122 ///////////////////////////////////////////////////////////////////////////// 2123 // 2124 // ScriptNodeDataSource public methods 2125 // 2126 ///////////////////////////////////////////////////////////////////////////// 2127 2128 /** 2129 * Creates a request callback that gets appended to the script URI. Implementers 2130 * can customize this string to match their server's query syntax. 2131 * 2132 * @method generateRequestCallback 2133 * @return {String} String fragment that gets appended to script URI that 2134 * specifies the callback function 2135 */ 2136 generateRequestCallback : function(id) { 2137 return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ; 2138 }, 2139 2140 /** 2141 * Overridable method gives implementers access to modify the URI before the dynamic 2142 * script node gets inserted. Implementers should take care not to return an 2143 * invalid URI. 2144 * 2145 * @method doBeforeGetScriptNode 2146 * @param {String} URI to the script 2147 * @return {String} URI to the script 2148 */ 2149 doBeforeGetScriptNode : function(sUri) { 2150 return sUri; 2151 }, 2152 2153 /** 2154 * Overriding method passes query to Get Utility. The returned 2155 * response is then forwarded to the handleResponse function. 2156 * 2157 * @method makeConnection 2158 * @param oRequest {Object} Request object. 2159 * @param oCallback {Object} Callback object literal. 2160 * @param oCaller {Object} (deprecated) Use oCallback.scope. 2161 * @return {Number} Transaction ID. 2162 */ 2163 makeConnection : function(oRequest, oCallback, oCaller) { 2164 var tId = DS._nTransactionId++; 2165 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); 2166 2167 // If there are no global pending requests, it is safe to purge global callback stack and global counter 2168 if(util.ScriptNodeDataSource._nPending === 0) { 2169 util.ScriptNodeDataSource.callbacks = []; 2170 util.ScriptNodeDataSource._nId = 0; 2171 } 2172 2173 // ID for this request 2174 var id = util.ScriptNodeDataSource._nId; 2175 util.ScriptNodeDataSource._nId++; 2176 2177 // Dynamically add handler function with a closure to the callback stack 2178 var oSelf = this; 2179 util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) { 2180 if((oSelf.asyncMode !== "ignoreStaleResponses")|| 2181 (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses 2182 2183 // Try to sniff data type if it has not been defined 2184 if(oSelf.responseType === DS.TYPE_UNKNOWN) { 2185 if(YAHOO.lang.isArray(oRawResponse)) { // array 2186 oSelf.responseType = DS.TYPE_JSARRAY; 2187 } 2188 // xml 2189 else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) { 2190 oSelf.responseType = DS.TYPE_XML; 2191 } 2192 else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table 2193 oSelf.responseType = DS.TYPE_HTMLTABLE; 2194 } 2195 else if(YAHOO.lang.isObject(oRawResponse)) { // json 2196 oSelf.responseType = DS.TYPE_JSON; 2197 } 2198 else if(YAHOO.lang.isString(oRawResponse)) { // text 2199 oSelf.responseType = DS.TYPE_TEXT; 2200 } 2201 } 2202 2203 oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); 2204 } 2205 else { 2206 YAHOO.log("DataSource ignored stale response for tId " + tId + "(" + oRequest + ")", "info", oSelf.toString()); 2207 } 2208 2209 delete util.ScriptNodeDataSource.callbacks[id]; 2210 }; 2211 2212 // We are now creating a request 2213 util.ScriptNodeDataSource._nPending++; 2214 var sUri = this.liveData + oRequest + this.generateRequestCallback(id); 2215 sUri = this.doBeforeGetScriptNode(sUri); 2216 YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString()); 2217 this.getUtility.script(sUri, 2218 {autopurge: true, 2219 onsuccess: util.ScriptNodeDataSource._bumpPendingDown, 2220 onfail: util.ScriptNodeDataSource._bumpPendingDown}); 2221 2222 return tId; 2223 } 2224 2225 }); 2226 2227 // Copy static members to ScriptNodeDataSource class 2228 lang.augmentObject(util.ScriptNodeDataSource, DS); 2229 2230 // Copy static members to ScriptNodeDataSource class 2231 lang.augmentObject(util.ScriptNodeDataSource, { 2232 2233 ///////////////////////////////////////////////////////////////////////////// 2234 // 2235 // ScriptNodeDataSource private static properties 2236 // 2237 ///////////////////////////////////////////////////////////////////////////// 2238 2239 /** 2240 * Unique ID to track requests. 2241 * 2242 * @property _nId 2243 * @type Number 2244 * @private 2245 * @static 2246 */ 2247 _nId : 0, 2248 2249 /** 2250 * Counter for pending requests. When this is 0, it is safe to purge callbacks 2251 * array. 2252 * 2253 * @property _nPending 2254 * @type Number 2255 * @private 2256 * @static 2257 */ 2258 _nPending : 0, 2259 2260 /** 2261 * Global array of callback functions, one for each request sent. 2262 * 2263 * @property callbacks 2264 * @type Function[] 2265 * @static 2266 */ 2267 callbacks : [] 2268 2269 }); 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 /****************************************************************************/ 2285 /****************************************************************************/ 2286 /****************************************************************************/ 2287 2288 /** 2289 * XHRDataSource class for accessing remote data via the YUI Connection Manager 2290 * Utility 2291 * 2292 * @namespace YAHOO.util 2293 * @class YAHOO.util.XHRDataSource 2294 * @extends YAHOO.util.DataSourceBase 2295 * @constructor 2296 * @param oLiveData {HTMLElement} Pointer to live data. 2297 * @param oConfigs {object} (optional) Object literal of configuration values. 2298 */ 2299 util.XHRDataSource = function(oLiveData, oConfigs) { 2300 this.dataType = DS.TYPE_XHR; 2301 this.connMgr = this.connMgr || util.Connect; 2302 oLiveData = oLiveData || ""; 2303 2304 util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 2305 }; 2306 2307 // XHRDataSource extends DataSourceBase 2308 lang.extend(util.XHRDataSource, DS, { 2309 2310 ///////////////////////////////////////////////////////////////////////////// 2311 // 2312 // XHRDataSource public properties 2313 // 2314 ///////////////////////////////////////////////////////////////////////////// 2315 2316 /** 2317 * Alias to YUI Connection Manager, to allow implementers to use a custom class. 2318 * 2319 * @property connMgr 2320 * @type Object 2321 * @default YAHOO.util.Connect 2322 */ 2323 connMgr: null, 2324 2325 /** 2326 * Defines request/response management in the following manner: 2327 * <dl> 2328 * <dt>queueRequests</dt> 2329 * <dd>If a request is already in progress, wait until response is returned 2330 * before sending the next request.</dd> 2331 * 2332 * <dt>cancelStaleRequests</dt> 2333 * <dd>If a request is already in progress, cancel it before sending the next 2334 * request.</dd> 2335 * 2336 * <dt>ignoreStaleResponses</dt> 2337 * <dd>Send all requests, but handle only the response for the most recently 2338 * sent request.</dd> 2339 * 2340 * <dt>allowAll</dt> 2341 * <dd>Send all requests and handle all responses.</dd> 2342 * 2343 * </dl> 2344 * 2345 * @property connXhrMode 2346 * @type String 2347 * @default "allowAll" 2348 */ 2349 connXhrMode: "allowAll", 2350 2351 /** 2352 * True if data is to be sent via POST. By default, data will be sent via GET. 2353 * 2354 * @property connMethodPost 2355 * @type Boolean 2356 * @default false 2357 */ 2358 connMethodPost: false, 2359 2360 /** 2361 * The connection timeout defines how many milliseconds the XHR connection will 2362 * wait for a server response. Any non-zero value will enable the Connection Manager's 2363 * Auto-Abort feature. 2364 * 2365 * @property connTimeout 2366 * @type Number 2367 * @default 0 2368 */ 2369 connTimeout: 0, 2370 2371 ///////////////////////////////////////////////////////////////////////////// 2372 // 2373 // XHRDataSource public methods 2374 // 2375 ///////////////////////////////////////////////////////////////////////////// 2376 2377 /** 2378 * Overriding method passes query to Connection Manager. The returned 2379 * response is then forwarded to the handleResponse function. 2380 * 2381 * @method makeConnection 2382 * @param oRequest {Object} Request object. 2383 * @param oCallback {Object} Callback object literal. 2384 * @param oCaller {Object} (deprecated) Use oCallback.scope. 2385 * @return {Number} Transaction ID. 2386 */ 2387 makeConnection : function(oRequest, oCallback, oCaller) { 2388 2389 var oRawResponse = null; 2390 var tId = DS._nTransactionId++; 2391 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); 2392 2393 // Set up the callback object and 2394 // pass the request in as a URL query and 2395 // forward the response to the handler 2396 var oSelf = this; 2397 var oConnMgr = this.connMgr; 2398 var oQueue = this._oQueue; 2399 2400 /** 2401 * Define Connection Manager success handler 2402 * 2403 * @method _xhrSuccess 2404 * @param oResponse {Object} HTTPXMLRequest object 2405 * @private 2406 */ 2407 var _xhrSuccess = function(oResponse) { 2408 // If response ID does not match last made request ID, 2409 // silently fail and wait for the next response 2410 if(oResponse && (this.connXhrMode == "ignoreStaleResponses") && 2411 (oResponse.tId != oQueue.conn.tId)) { 2412 YAHOO.log("Ignored stale response", "warn", this.toString()); 2413 return null; 2414 } 2415 // Error if no response 2416 else if(!oResponse) { 2417 this.fireEvent("dataErrorEvent", {request:oRequest, response:null, 2418 callback:oCallback, caller:oCaller, 2419 message:DS.ERROR_DATANULL}); 2420 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString()); 2421 2422 // Send error response back to the caller with the error flag on 2423 DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller); 2424 2425 return null; 2426 } 2427 // Forward to handler 2428 else { 2429 // Try to sniff data type if it has not been defined 2430 if(this.responseType === DS.TYPE_UNKNOWN) { 2431 var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null; 2432 if(ctype) { 2433 // xml 2434 if(ctype.indexOf("text/xml") > -1) { 2435 this.responseType = DS.TYPE_XML; 2436 } 2437 else if(ctype.indexOf("application/json") > -1) { // json 2438 this.responseType = DS.TYPE_JSON; 2439 } 2440 else if(ctype.indexOf("text/plain") > -1) { // text 2441 this.responseType = DS.TYPE_TEXT; 2442 } 2443 } 2444 } 2445 this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId); 2446 } 2447 }; 2448 2449 /** 2450 * Define Connection Manager failure handler 2451 * 2452 * @method _xhrFailure 2453 * @param oResponse {Object} HTTPXMLRequest object 2454 * @private 2455 */ 2456 var _xhrFailure = function(oResponse) { 2457 this.fireEvent("dataErrorEvent", {request:oRequest, response: oResponse, 2458 callback:oCallback, caller:oCaller, 2459 message:DS.ERROR_DATAINVALID}); 2460 YAHOO.log(DS.ERROR_DATAINVALID + ": " + 2461 oResponse.statusText, "error", this.toString()); 2462 2463 // Backward compatibility 2464 if(lang.isString(this.liveData) && lang.isString(oRequest) && 2465 (this.liveData.lastIndexOf("?") !== this.liveData.length-1) && 2466 (oRequest.indexOf("?") !== 0)){ 2467 YAHOO.log("DataSources using XHR no longer automatically supply " + 2468 "a \"?\" between the host and query parameters" + 2469 " -- please check that the request URL is correct", "warn", this.toString()); 2470 } 2471 2472 // Send failure response back to the caller with the error flag on 2473 oResponse = oResponse || {}; 2474 oResponse.error = true; 2475 DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller); 2476 2477 return null; 2478 }; 2479 2480 /** 2481 * Define Connection Manager callback object 2482 * 2483 * @property _xhrCallback 2484 * @param oResponse {Object} HTTPXMLRequest object 2485 * @private 2486 */ 2487 var _xhrCallback = { 2488 success:_xhrSuccess, 2489 failure:_xhrFailure, 2490 scope: this 2491 }; 2492 2493 // Apply Connection Manager timeout 2494 if(lang.isNumber(this.connTimeout)) { 2495 _xhrCallback.timeout = this.connTimeout; 2496 } 2497 2498 // Cancel stale requests 2499 if(this.connXhrMode == "cancelStaleRequests") { 2500 // Look in queue for stale requests 2501 if(oQueue.conn) { 2502 if(oConnMgr.abort) { 2503 oConnMgr.abort(oQueue.conn); 2504 oQueue.conn = null; 2505 YAHOO.log("Canceled stale request", "warn", this.toString()); 2506 } 2507 else { 2508 YAHOO.log("Could not find Connection Manager abort() function", "error", this.toString()); 2509 } 2510 } 2511 } 2512 2513 // Get ready to send the request URL 2514 if(oConnMgr && oConnMgr.asyncRequest) { 2515 var sLiveData = this.liveData; 2516 var isPost = this.connMethodPost; 2517 var sMethod = (isPost) ? "POST" : "GET"; 2518 // Validate request 2519 var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest; 2520 var sRequest = (isPost) ? oRequest : null; 2521 2522 // Send the request right away 2523 if(this.connXhrMode != "queueRequests") { 2524 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); 2525 } 2526 // Queue up then send the request 2527 else { 2528 // Found a request already in progress 2529 if(oQueue.conn) { 2530 var allRequests = oQueue.requests; 2531 // Add request to queue 2532 allRequests.push({request:oRequest, callback:_xhrCallback}); 2533 2534 // Interval needs to be started 2535 if(!oQueue.interval) { 2536 oQueue.interval = setInterval(function() { 2537 // Connection is in progress 2538 if(oConnMgr.isCallInProgress(oQueue.conn)) { 2539 return; 2540 } 2541 else { 2542 // Send next request 2543 if(allRequests.length > 0) { 2544 // Validate request 2545 sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request; 2546 sRequest = (isPost) ? allRequests[0].request : null; 2547 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest); 2548 2549 // Remove request from queue 2550 allRequests.shift(); 2551 } 2552 // No more requests 2553 else { 2554 clearInterval(oQueue.interval); 2555 oQueue.interval = null; 2556 } 2557 } 2558 }, 50); 2559 } 2560 } 2561 // Nothing is in progress 2562 else { 2563 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); 2564 } 2565 } 2566 } 2567 else { 2568 YAHOO.log("Could not find Connection Manager asyncRequest() function", "error", this.toString()); 2569 // Send null response back to the caller with the error flag on 2570 DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller); 2571 } 2572 2573 return tId; 2574 } 2575 2576 }); 2577 2578 // Copy static members to XHRDataSource class 2579 lang.augmentObject(util.XHRDataSource, DS); 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 /****************************************************************************/ 2594 /****************************************************************************/ 2595 /****************************************************************************/ 2596 2597 /** 2598 * Factory class for creating a BaseDataSource subclass instance. The sublcass is 2599 * determined by oLiveData's type, unless the dataType config is explicitly passed in. 2600 * 2601 * @namespace YAHOO.util 2602 * @class YAHOO.util.DataSource 2603 * @constructor 2604 * @param oLiveData {HTMLElement} Pointer to live data. 2605 * @param oConfigs {object} (optional) Object literal of configuration values. 2606 */ 2607 util.DataSource = function(oLiveData, oConfigs) { 2608 oConfigs = oConfigs || {}; 2609 2610 // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type. 2611 var dataType = oConfigs.dataType; 2612 if(dataType) { 2613 if(dataType == DS.TYPE_LOCAL) { 2614 return new util.LocalDataSource(oLiveData, oConfigs); 2615 } 2616 else if(dataType == DS.TYPE_XHR) { 2617 return new util.XHRDataSource(oLiveData, oConfigs); 2618 } 2619 else if(dataType == DS.TYPE_SCRIPTNODE) { 2620 return new util.ScriptNodeDataSource(oLiveData, oConfigs); 2621 } 2622 else if(dataType == DS.TYPE_JSFUNCTION) { 2623 return new util.FunctionDataSource(oLiveData, oConfigs); 2624 } 2625 } 2626 2627 if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr 2628 return new util.XHRDataSource(oLiveData, oConfigs); 2629 } 2630 else if(YAHOO.lang.isFunction(oLiveData)) { 2631 return new util.FunctionDataSource(oLiveData, oConfigs); 2632 } 2633 else { // ultimate default is local 2634 return new util.LocalDataSource(oLiveData, oConfigs); 2635 } 2636 }; 2637 2638 // Copy static members to DataSource class 2639 lang.augmentObject(util.DataSource, DS); 2640 2641 })(); 2642 2643 /****************************************************************************/ 2644 /****************************************************************************/ 2645 /****************************************************************************/ 2646 2647 /** 2648 * The static Number class provides helper functions to deal with data of type 2649 * Number. 2650 * 2651 * @namespace YAHOO.util 2652 * @requires yahoo 2653 * @class Number 2654 * @static 2655 */ 2656 YAHOO.util.Number = { 2657 2658 /** 2659 * Takes a native JavaScript Number and formats to a string for display. 2660 * 2661 * @method format 2662 * @param nData {Number} Number. 2663 * @param oConfig {Object} (Optional) Optional configuration values: 2664 * <dl> 2665 * <dt>format</dt> 2666 * <dd>String used as a template for formatting positive numbers. 2667 * {placeholders} in the string are applied from the values in this 2668 * config object. {number} is used to indicate where the numeric portion 2669 * of the output goes. For example "{prefix}{number} per item" 2670 * might yield "$5.25 per item". The only required 2671 * {placeholder} is {number}.</dd> 2672 * 2673 * <dt>negativeFormat</dt> 2674 * <dd>Like format, but applied to negative numbers. If set to null, 2675 * defaults from the configured format, prefixed with -. This is 2676 * separate from format to support formats like "($12,345.67)". 2677 * 2678 * <dt>prefix {String} (deprecated, use format/negativeFormat)</dt> 2679 * <dd>String prepended before each number, like a currency designator "$"</dd> 2680 * <dt>decimalPlaces {Number}</dt> 2681 * <dd>Number of decimal places to round.</dd> 2682 * 2683 * <dt>decimalSeparator {String}</dt> 2684 * <dd>Decimal separator</dd> 2685 * 2686 * <dt>thousandsSeparator {String}</dt> 2687 * <dd>Thousands separator</dd> 2688 * 2689 * <dt>suffix {String} (deprecated, use format/negativeFormat)</dt> 2690 * <dd>String appended after each number, like " items" (note the space)</dd> 2691 * </dl> 2692 * @return {String} Formatted number for display. Note, the following values 2693 * return as "": null, undefined, NaN, "". 2694 */ 2695 format : function(n, cfg) { 2696 if (n === '' || n === null || !isFinite(n)) { 2697 return ''; 2698 } 2699 2700 n = +n; 2701 cfg = YAHOO.lang.merge(YAHOO.util.Number.format.defaults, (cfg || {})); 2702 2703 var stringN = n+'', 2704 absN = Math.abs(n), 2705 places = cfg.decimalPlaces || 0, 2706 sep = cfg.thousandsSeparator, 2707 negFmt = cfg.negativeFormat || ('-' + cfg.format), 2708 s, bits, i, precision; 2709 2710 if (negFmt.indexOf('#') > -1) { 2711 // for backward compatibility of negativeFormat supporting '-#' 2712 negFmt = negFmt.replace(/#/, cfg.format); 2713 } 2714 2715 if (places < 0) { 2716 // Get rid of the decimal info 2717 s = absN - (absN % 1) + ''; 2718 i = s.length + places; 2719 2720 // avoid 123 vs decimalPlaces -4 (should return "0") 2721 if (i > 0) { 2722 // leverage toFixed by making 123 => 0.123 for the rounding 2723 // operation, then add the appropriate number of zeros back on 2724 s = Number('.' + s).toFixed(i).slice(2) + 2725 new Array(s.length - i + 1).join('0'); 2726 } else { 2727 s = "0"; 2728 } 2729 } else { 2730 // Avoid toFixed on floats: 2731 // Bug 2528976 2732 // Bug 2528977 2733 var unfloatedN = absN+''; 2734 if(places > 0 || unfloatedN.indexOf('.') > 0) { 2735 var power = Math.pow(10, places); 2736 s = Math.round(absN * power) / power + ''; 2737 var dot = s.indexOf('.'), 2738 padding, zeroes; 2739 2740 // Add padding 2741 if(dot < 0) { 2742 padding = places; 2743 zeroes = (Math.pow(10, padding) + '').substring(1); 2744 if(places > 0) { 2745 s = s + '.' + zeroes; 2746 } 2747 } 2748 else { 2749 padding = places - (s.length - dot - 1); 2750 zeroes = (Math.pow(10, padding) + '').substring(1); 2751 s = s + zeroes; 2752 } 2753 } 2754 else { 2755 s = absN.toFixed(places)+''; 2756 } 2757 } 2758 2759 bits = s.split(/\D/); 2760 2761 if (absN >= 1000) { 2762 i = bits[0].length % 3 || 3; 2763 2764 bits[0] = bits[0].slice(0,i) + 2765 bits[0].slice(i).replace(/(\d{3})/g, sep + '$1'); 2766 2767 } 2768 2769 return YAHOO.util.Number.format._applyFormat( 2770 (n < 0 ? negFmt : cfg.format), 2771 bits.join(cfg.decimalSeparator), 2772 cfg); 2773 } 2774 }; 2775 2776 /** 2777 * <p>Default values for Number.format behavior. Override properties of this 2778 * object if you want every call to Number.format in your system to use 2779 * specific presets.</p> 2780 * 2781 * <p>Available keys include:</p> 2782 * <ul> 2783 * <li>format</li> 2784 * <li>negativeFormat</li> 2785 * <li>decimalSeparator</li> 2786 * <li>decimalPlaces</li> 2787 * <li>thousandsSeparator</li> 2788 * <li>prefix/suffix or any other token you want to use in the format templates</li> 2789 * </ul> 2790 * 2791 * @property Number.format.defaults 2792 * @type {Object} 2793 * @static 2794 */ 2795 YAHOO.util.Number.format.defaults = { 2796 format : '{prefix}{number}{suffix}', 2797 negativeFormat : null, // defaults to -(format) 2798 decimalSeparator : '.', 2799 decimalPlaces : null, 2800 thousandsSeparator : '' 2801 }; 2802 2803 /** 2804 * Apply any special formatting to the "d,ddd.dd" string. Takes either the 2805 * cfg.format or cfg.negativeFormat template and replaces any {placeholders} 2806 * with either the number or a value from a so-named property of the config 2807 * object. 2808 * 2809 * @method Number.format._applyFormat 2810 * @static 2811 * @param tmpl {String} the cfg.format or cfg.numberFormat template string 2812 * @param num {String} the number with separators and decimalPlaces applied 2813 * @param data {Object} the config object, used here to populate {placeholder}s 2814 * @return {String} the number with any decorators added 2815 */ 2816 YAHOO.util.Number.format._applyFormat = function (tmpl, num, data) { 2817 return tmpl.replace(/\{(\w+)\}/g, function (_, token) { 2818 return token === 'number' ? num : 2819 token in data ? data[token] : ''; 2820 }); 2821 }; 2822 2823 2824 /****************************************************************************/ 2825 /****************************************************************************/ 2826 /****************************************************************************/ 2827 2828 (function () { 2829 2830 var xPad=function (x, pad, r) 2831 { 2832 if(typeof r === 'undefined') 2833 { 2834 r=10; 2835 } 2836 for( ; parseInt(x, 10)<r && r>1; r/=10) { 2837 x = pad.toString() + x; 2838 } 2839 return x.toString(); 2840 }; 2841 2842 2843 /** 2844 * The static Date class provides helper functions to deal with data of type Date. 2845 * 2846 * @namespace YAHOO.util 2847 * @requires yahoo 2848 * @class Date 2849 * @static 2850 */ 2851 var Dt = { 2852 formats: { 2853 a: function (d, l) { return l.a[d.getDay()]; }, 2854 A: function (d, l) { return l.A[d.getDay()]; }, 2855 b: function (d, l) { return l.b[d.getMonth()]; }, 2856 B: function (d, l) { return l.B[d.getMonth()]; }, 2857 C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); }, 2858 d: ['getDate', '0'], 2859 e: ['getDate', ' '], 2860 g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); }, 2861 G: function (d) { 2862 var y = d.getFullYear(); 2863 var V = parseInt(Dt.formats.V(d), 10); 2864 var W = parseInt(Dt.formats.W(d), 10); 2865 2866 if(W > V) { 2867 y++; 2868 } else if(W===0 && V>=52) { 2869 y--; 2870 } 2871 2872 return y; 2873 }, 2874 H: ['getHours', '0'], 2875 I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); }, 2876 j: function (d) { 2877 var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT'); 2878 var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT'); 2879 var ms = gmdate - gmd_1; 2880 var doy = parseInt(ms/60000/60/24, 10)+1; 2881 return xPad(doy, 0, 100); 2882 }, 2883 k: ['getHours', ' '], 2884 l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); }, 2885 m: function (d) { return xPad(d.getMonth()+1, 0); }, 2886 M: ['getMinutes', '0'], 2887 p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; }, 2888 P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; }, 2889 s: function (d, l) { return parseInt(d.getTime()/1000, 10); }, 2890 S: ['getSeconds', '0'], 2891 u: function (d) { var dow = d.getDay(); return dow===0?7:dow; }, 2892 U: function (d) { 2893 var doy = parseInt(Dt.formats.j(d), 10); 2894 var rdow = 6-d.getDay(); 2895 var woy = parseInt((doy+rdow)/7, 10); 2896 return xPad(woy, 0); 2897 }, 2898 V: function (d) { 2899 var woy = parseInt(Dt.formats.W(d), 10); 2900 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay(); 2901 // First week is 01 and not 00 as in the case of %U and %W, 2902 // so we add 1 to the final result except if day 1 of the year 2903 // is a Monday (then %W returns 01). 2904 // We also need to subtract 1 if the day 1 of the year is 2905 // Friday-Sunday, so the resulting equation becomes: 2906 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1); 2907 if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4) 2908 { 2909 idow = 1; 2910 } 2911 else if(idow === 0) 2912 { 2913 idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31')); 2914 } 2915 2916 return xPad(idow, 0); 2917 }, 2918 w: 'getDay', 2919 W: function (d) { 2920 var doy = parseInt(Dt.formats.j(d), 10); 2921 var rdow = 7-Dt.formats.u(d); 2922 var woy = parseInt((doy+rdow)/7, 10); 2923 return xPad(woy, 0, 10); 2924 }, 2925 y: function (d) { return xPad(d.getFullYear()%100, 0); }, 2926 Y: 'getFullYear', 2927 z: function (d) { 2928 var o = d.getTimezoneOffset(); 2929 var H = xPad(parseInt(Math.abs(o/60), 10), 0); 2930 var M = xPad(Math.abs(o%60), 0); 2931 return (o>0?'-':'+') + H + M; 2932 }, 2933 Z: function (d) { 2934 var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, ''); 2935 if(tz.length > 4) { 2936 tz = Dt.formats.z(d); 2937 } 2938 return tz; 2939 }, 2940 '%': function (d) { return '%'; } 2941 }, 2942 2943 aggregates: { 2944 c: 'locale', 2945 D: '%m/%d/%y', 2946 F: '%Y-%m-%d', 2947 h: '%b', 2948 n: '\n', 2949 r: 'locale', 2950 R: '%H:%M', 2951 t: '\t', 2952 T: '%H:%M:%S', 2953 x: 'locale', 2954 X: 'locale' 2955 //'+': '%a %b %e %T %Z %Y' 2956 }, 2957 2958 /** 2959 * Takes a native JavaScript Date and formats to string for display to user. 2960 * 2961 * @method format 2962 * @param oDate {Date} Date. 2963 * @param oConfig {Object} (Optional) Object literal of configuration values: 2964 * <dl> 2965 * <dt>format <String></dt> 2966 * <dd> 2967 * <p> 2968 * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at 2969 * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a> 2970 * </p> 2971 * <p> 2972 * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a> 2973 * </p> 2974 * <p> 2975 * This javascript implementation supports all the PHP specifiers and a few more. The full list is below: 2976 * </p> 2977 * <dl> 2978 * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd> 2979 * <dt>%A</dt> <dd>full weekday name according to the current locale</dd> 2980 * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd> 2981 * <dt>%B</dt> <dd>full month name according to the current locale</dd> 2982 * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd> 2983 * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd> 2984 * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd> 2985 * <dt>%D</dt> <dd>same as %m/%d/%y</dd> 2986 * <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd> 2987 * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd> 2988 * <dt>%g</dt> <dd>like %G, but without the century</dd> 2989 * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd> 2990 * <dt>%h</dt> <dd>same as %b</dd> 2991 * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd> 2992 * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd> 2993 * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd> 2994 * <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd> 2995 * <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd> 2996 * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd> 2997 * <dt>%M</dt> <dd>minute as a decimal number</dd> 2998 * <dt>%n</dt> <dd>newline character</dd> 2999 * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd> 3000 * <dt>%P</dt> <dd>like %p, but lower case</dd> 3001 * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd> 3002 * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd> 3003 * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd> 3004 * <dt>%S</dt> <dd>second as a decimal number</dd> 3005 * <dt>%t</dt> <dd>tab character</dd> 3006 * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd> 3007 * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd> 3008 * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the 3009 * first Sunday as the first day of the first week</dd> 3010 * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number, 3011 * range 01 to 53, where week 1 is the first week that has at least 4 days 3012 * in the current year, and with Monday as the first day of the week.</dd> 3013 * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd> 3014 * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the 3015 * first Monday as the first day of the first week</dd> 3016 * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd> 3017 * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd> 3018 * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd> 3019 * <dt>%Y</dt> <dd>year as a decimal number including the century</dd> 3020 * <dt>%z</dt> <dd>numerical time zone representation</dd> 3021 * <dt>%Z</dt> <dd>time zone name or abbreviation</dd> 3022 * <dt>%%</dt> <dd>a literal `%' character</dd> 3023 * </dl> 3024 * </dd> 3025 * </dl> 3026 * @param sLocale {String} (Optional) The locale to use when displaying days of week, 3027 * months of the year, and other locale specific strings. The following locales are 3028 * built in: 3029 * <dl> 3030 * <dt>en</dt> 3031 * <dd>English</dd> 3032 * <dt>en-US</dt> 3033 * <dd>US English</dd> 3034 * <dt>en-GB</dt> 3035 * <dd>British English</dd> 3036 * <dt>en-AU</dt> 3037 * <dd>Australian English (identical to British English)</dd> 3038 * </dl> 3039 * More locales may be added by subclassing of YAHOO.util.DateLocale. 3040 * See YAHOO.util.DateLocale for more information. 3041 * @return {HTML} Formatted date for display. Non-date values are passed 3042 * through as-is. 3043 * @sa YAHOO.util.DateLocale 3044 */ 3045 format : function (oDate, oConfig, sLocale) { 3046 oConfig = oConfig || {}; 3047 3048 if(!(oDate instanceof Date)) { 3049 return YAHOO.lang.isValue(oDate) ? oDate : ""; 3050 } 3051 3052 var format = oConfig.format || "%m/%d/%Y"; 3053 3054 // Be backwards compatible, support strings that are 3055 // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY 3056 if(format === 'YYYY/MM/DD') { 3057 format = '%Y/%m/%d'; 3058 } else if(format === 'DD/MM/YYYY') { 3059 format = '%d/%m/%Y'; 3060 } else if(format === 'MM/DD/YYYY') { 3061 format = '%m/%d/%Y'; 3062 } 3063 // end backwards compatibility block 3064 3065 sLocale = sLocale || "en"; 3066 3067 // Make sure we have a definition for the requested locale, or default to en. 3068 if(!(sLocale in YAHOO.util.DateLocale)) { 3069 if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) { 3070 sLocale = sLocale.replace(/-[a-zA-Z]+$/, ''); 3071 } else { 3072 sLocale = "en"; 3073 } 3074 } 3075 3076 var aLocale = YAHOO.util.DateLocale[sLocale]; 3077 3078 var replace_aggs = function (m0, m1) { 3079 var f = Dt.aggregates[m1]; 3080 return (f === 'locale' ? aLocale[m1] : f); 3081 }; 3082 3083 var replace_formats = function (m0, m1) { 3084 var f = Dt.formats[m1]; 3085 if(typeof f === 'string') { // string => built in date function 3086 return oDate[f](); 3087 } else if(typeof f === 'function') { // function => our own function 3088 return f.call(oDate, oDate, aLocale); 3089 } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding 3090 return xPad(oDate[f[0]](), f[1]); 3091 } else { 3092 return m1; 3093 } 3094 }; 3095 3096 // First replace aggregates (run in a loop because an agg may be made up of other aggs) 3097 while(format.match(/%[cDFhnrRtTxX]/)) { 3098 format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs); 3099 } 3100 3101 // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a) 3102 var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats); 3103 3104 replace_aggs = replace_formats = undefined; 3105 3106 return str; 3107 } 3108 }; 3109 3110 YAHOO.namespace("YAHOO.util"); 3111 YAHOO.util.Date = Dt; 3112 3113 /** 3114 * The DateLocale class is a container and base class for all 3115 * localised date strings used by YAHOO.util.Date. It is used 3116 * internally, but may be extended to provide new date localisations. 3117 * 3118 * To create your own DateLocale, follow these steps: 3119 * <ol> 3120 * <li>Find an existing locale that matches closely with your needs</li> 3121 * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing 3122 * matches.</li> 3123 * <li>Create your own class as an extension of the base class using 3124 * YAHOO.lang.merge, and add your own localisations where needed.</li> 3125 * </ol> 3126 * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB'] 3127 * classes which extend YAHOO.util.DateLocale['en']. 3128 * 3129 * For example, to implement locales for French french and Canadian french, 3130 * we would do the following: 3131 * <ol> 3132 * <li>For French french, we have no existing similar locale, so use 3133 * YAHOO.util.DateLocale as the base, and extend it: 3134 * <pre> 3135 * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, { 3136 * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'], 3137 * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], 3138 * b: ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'], 3139 * B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'], 3140 * c: '%a %d %b %Y %T %Z', 3141 * p: ['', ''], 3142 * P: ['', ''], 3143 * x: '%d.%m.%Y', 3144 * X: '%T' 3145 * }); 3146 * </pre> 3147 * </li> 3148 * <li>For Canadian french, we start with French french and change the meaning of \%x: 3149 * <pre> 3150 * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], { 3151 * x: '%Y-%m-%d' 3152 * }); 3153 * </pre> 3154 * </li> 3155 * </ol> 3156 * 3157 * With that, you can use your new locales: 3158 * <pre> 3159 * var d = new Date("2008/04/22"); 3160 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr"); 3161 * </pre> 3162 * will return: 3163 * <pre> 3164 * mardi, 22 avril == 22.04.2008 3165 * </pre> 3166 * And 3167 * <pre> 3168 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA"); 3169 * </pre> 3170 * Will return: 3171 * <pre> 3172 * mardi, 22 avril == 2008-04-22 3173 * </pre> 3174 * @namespace YAHOO.util 3175 * @requires yahoo 3176 * @class DateLocale 3177 */ 3178 YAHOO.util.DateLocale = { 3179 a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 3180 A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 3181 b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 3182 B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 3183 c: '%a %d %b %Y %T %Z', 3184 p: ['AM', 'PM'], 3185 P: ['am', 'pm'], 3186 r: '%I:%M:%S %p', 3187 x: '%d/%m/%y', 3188 X: '%T' 3189 }; 3190 3191 YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {}); 3192 3193 YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { 3194 c: '%a %d %b %Y %I:%M:%S %p %Z', 3195 x: '%m/%d/%Y', 3196 X: '%I:%M:%S %p' 3197 }); 3198 3199 YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { 3200 r: '%l:%M:%S %P %Z' 3201 }); 3202 YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']); 3203 3204 })(); 3205 3206 YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.9.0", build: "2800"}); 3207 3208 }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-event"], "optional": ["yui2-connection"]});
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Thu Aug 11 10:00:09 2016 | Cross-referenced by PHPXref 0.7.1 |