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