2 Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 * The DataSource utility provides a common configurable interface for widgets
9 * to access a variety of data, from JavaScript arrays to online servers over
12 * @namespace YAHOO.util
14 * @requires yahoo, event
15 * @optional connection
16 * @title DataSource Utility
20 /****************************************************************************/
21 /****************************************************************************/
22 /****************************************************************************/
25 * The DataSource class defines and manages a live set of data for widgets to
26 * interact with. Examples of live databases include in-memory
27 * local data such as a JavaScript array, a JavaScript function, or JSON, or
28 * remote data such as data retrieved through an XHR connection.
31 * @uses YAHOO.util.EventProvider
33 * @param oLiveData {Object} Pointer to live database.
34 * @param oConfigs {Object} (optional) Object literal of configuration values.
36 YAHOO
.util
.DataSource = function(oLiveData
, oConfigs
) {
37 // Set any config params passed in to override defaults
38 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
39 for(var sConfig
in oConfigs
) {
41 this[sConfig
] = oConfigs
[sConfig
];
47 YAHOO
.log("Could not instantiate DataSource due to invalid live database",
48 "error", this.toString());
52 if(oLiveData
.nodeType
&& oLiveData
.nodeType
== 9) {
53 this.dataType
= YAHOO
.util
.DataSource
.TYPE_XML
;
55 else if(YAHOO
.lang
.isArray(oLiveData
)) {
56 this.dataType
= YAHOO
.util
.DataSource
.TYPE_JSARRAY
;
58 else if(YAHOO
.lang
.isString(oLiveData
)) {
59 this.dataType
= YAHOO
.util
.DataSource
.TYPE_XHR
;
61 else if(YAHOO
.lang
.isFunction(oLiveData
)) {
62 this.dataType
= YAHOO
.util
.DataSource
.TYPE_JSFUNCTION
;
64 else if(oLiveData
.nodeName
&& (oLiveData
.nodeName
.toLowerCase() == "table")) {
65 this.dataType
= YAHOO
.util
.DataSource
.TYPE_HTMLTABLE
;
67 else if(YAHOO
.lang
.isObject(oLiveData
)) {
68 this.dataType
= YAHOO
.util
.DataSource
.TYPE_JSON
;
71 this.dataType
= YAHOO
.util
.DataSource
.TYPE_UNKNOWN
;
74 this.liveData
= oLiveData
;
75 this._oQueue
= {interval
:null, conn
:null, requests
:[]};
78 // Validate and initialize public configs
79 var maxCacheEntries
= this.maxCacheEntries
;
80 if(!YAHOO
.lang
.isNumber(maxCacheEntries
) || (maxCacheEntries
< 0)) {
84 // Initialize local cache
85 if(maxCacheEntries
> 0 && !this._aCache
) {
87 YAHOO
.log("Cache initialized", "info", this.toString());
90 this._sName
= "DataSource instance" + YAHOO
.util
.DataSource
._nIndex
;
91 YAHOO
.util
.DataSource
._nIndex
++;
92 YAHOO
.log("DataSource initialized", "info", this.toString());
95 /////////////////////////////////////////////////////////////////////////////
99 /////////////////////////////////////////////////////////////////////////////
102 * Fired when a request is made to the local cache.
104 * @event cacheRequestEvent
105 * @param oArgs.request {Object} The request object.
106 * @param oArgs.callback {Function} The callback function.
107 * @param oArgs.caller {Object} The parent object of the callback function.
109 this.createEvent("cacheRequestEvent");
112 * Fired when data is retrieved from the local cache.
114 * @event getCachedResponseEvent
115 * @param oArgs.request {Object} The request object.
116 * @param oArgs.response {Object} The response object.
117 * @param oArgs.callback {Function} The callback function.
118 * @param oArgs.caller {Object} The parent object of the callback function.
119 * @param oArgs.tId {Number} Transaction ID.
121 this.createEvent("cacheResponseEvent");
124 * Fired when a request is sent to the live data source.
126 * @event requestEvent
127 * @param oArgs.request {Object} The request object.
128 * @param oArgs.callback {Function} The callback function.
129 * @param oArgs.caller {Object} The parent object of the callback function.
131 this.createEvent("requestEvent");
134 * Fired when live data source sends response.
136 * @event responseEvent
137 * @param oArgs.request {Object} The request object.
138 * @param oArgs.response {Object} The raw response object.
139 * @param oArgs.callback {Function} The callback function.
140 * @param oArgs.caller {Object} The parent object of the callback function.
142 this.createEvent("responseEvent");
145 * Fired when response is parsed.
147 * @event responseParseEvent
148 * @param oArgs.request {Object} The request object.
149 * @param oArgs.response {Object} The parsed response object.
150 * @param oArgs.callback {Function} The callback function.
151 * @param oArgs.caller {Object} The parent object of the callback function.
153 this.createEvent("responseParseEvent");
156 * Fired when response is cached.
158 * @event responseCacheEvent
159 * @param oArgs.request {Object} The request object.
160 * @param oArgs.response {Object} The parsed response object.
161 * @param oArgs.callback {Function} The callback function.
162 * @param oArgs.caller {Object} The parent object of the callback function.
164 this.createEvent("responseCacheEvent");
166 * Fired when an error is encountered with the live data source.
168 * @event dataErrorEvent
169 * @param oArgs.request {Object} The request object.
170 * @param oArgs.callback {Function} The callback function.
171 * @param oArgs.caller {Object} The parent object of the callback function.
172 * @param oArgs.message {String} The error message.
174 this.createEvent("dataErrorEvent");
177 * Fired when the local cache is flushed.
179 * @event cacheFlushEvent
181 this.createEvent("cacheFlushEvent");
184 YAHOO
.augment(YAHOO
.util
.DataSource
, YAHOO
.util
.EventProvider
);
186 /////////////////////////////////////////////////////////////////////////////
190 /////////////////////////////////////////////////////////////////////////////
195 * @property TYPE_UNKNOWN
200 YAHOO
.util
.DataSource
.TYPE_UNKNOWN
= -1;
203 * Type is a JavaScript Array.
205 * @property TYPE_JSARRAY
210 YAHOO
.util
.DataSource
.TYPE_JSARRAY
= 0;
213 * Type is a JavaScript Function.
215 * @property TYPE_JSFUNCTION
220 YAHOO
.util
.DataSource
.TYPE_JSFUNCTION
= 1;
223 * Type is hosted on a server via an XHR connection.
230 YAHOO
.util
.DataSource
.TYPE_XHR
= 2;
235 * @property TYPE_JSON
240 YAHOO
.util
.DataSource
.TYPE_JSON
= 3;
250 YAHOO
.util
.DataSource
.TYPE_XML
= 4;
253 * Type is plain text.
255 * @property TYPE_TEXT
260 YAHOO
.util
.DataSource
.TYPE_TEXT
= 5;
263 * Type is an HTML TABLE element.
265 * @property TYPE_HTMLTABLE
270 YAHOO
.util
.DataSource
.TYPE_HTMLTABLE
= 6;
273 * Error message for invalid dataresponses.
275 * @property ERROR_DATAINVALID
278 * @default "Invalid data"
280 YAHOO
.util
.DataSource
.ERROR_DATAINVALID
= "Invalid data";
283 * Error message for null data responses.
285 * @property ERROR_DATANULL
288 * @default "Null data"
290 YAHOO
.util
.DataSource
.ERROR_DATANULL
= "Null data";
294 /////////////////////////////////////////////////////////////////////////////
298 /////////////////////////////////////////////////////////////////////////////
301 * Internal class variable to index multiple DataSource instances.
303 * @property DataSource._nIndex
308 YAHOO
.util
.DataSource
._nIndex
= 0;
311 * Internal class variable to assign unique transaction IDs.
313 * @property DataSource._nTransactionId
318 YAHOO
.util
.DataSource
._nTransactionId
= 0;
321 * Name of DataSource instance.
327 YAHOO
.util
.DataSource
.prototype._sName
= null;
330 * Local cache of data result object literals indexed chronologically.
336 YAHOO
.util
.DataSource
.prototype._aCache
= null;
339 * Local queue of request connections, enabled if queue needs to be managed.
345 YAHOO
.util
.DataSource
.prototype._oQueue
= null;
347 /////////////////////////////////////////////////////////////////////////////
351 /////////////////////////////////////////////////////////////////////////////
355 /////////////////////////////////////////////////////////////////////////////
357 // Public member variables
359 /////////////////////////////////////////////////////////////////////////////
362 * Max size of the local cache. Set to 0 to turn off caching. Caching is
363 * useful to reduce the number of server connections. Recommended only for data
364 * sources that return comprehensive results for queries or when stale data is
367 * @property maxCacheEntries
371 YAHOO
.util
.DataSource
.prototype.maxCacheEntries
= 0;
374 * Pointer to live database.
379 YAHOO
.util
.DataSource
.prototype.liveData
= null;
382 * Where the live data is held.
386 * @default YAHOO.util.DataSource.TYPE_UNKNOWN
389 YAHOO
.util
.DataSource
.prototype.dataType
= YAHOO
.util
.DataSource
.TYPE_UNKNOWN
;
392 * Format of response.
394 * @property responseType
396 * @default YAHOO.util.DataSource.TYPE_UNKNOWN
398 YAHOO
.util
.DataSource
.prototype.responseType
= YAHOO
.util
.DataSource
.TYPE_UNKNOWN
;
401 * Response schema object literal takes a combination of the following properties:
404 * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
405 * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
406 * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
407 * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
408 * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
409 * such as: {key:"fieldname",parser:YAHOO.util.DataSource.parseDate}</dd>
412 * @property responseSchema
415 YAHOO
.util
.DataSource
.prototype.responseSchema
= null;
418 * Alias to YUI Connection Manager. Allows implementers to specify their own
419 * subclasses of the YUI Connection Manager utility.
423 * @default YAHOO.util.Connect
425 YAHOO
.util
.DataSource
.prototype.connMgr
= null;
428 * If data is accessed over XHR via Connection Manager, this setting defines
429 * request/response management in the following manner:
431 * <dt>queueRequests</dt>
432 * <dd>If a request is already in progress, wait until response is returned
433 * before sending the next request.</dd>
435 * <dt>cancelStaleRequests</dt>
436 * <dd>If a request is already in progress, cancel it before sending the next
439 * <dt>ignoreStaleResponses</dt>
440 * <dd>Send all requests, but handle only the response for the most recently
444 * <dd>Send all requests and handle all responses.</dd>
448 * @property connXhrMode
450 * @default "allowAll"
452 YAHOO
.util
.DataSource
.prototype.connXhrMode
= "allowAll";
455 * If data is accessed over XHR via Connection Manager, true if data should be
456 * sent via POST, otherwise data will be sent via GET.
458 * @property connMethodPost
462 YAHOO
.util
.DataSource
.prototype.connMethodPost
= false;
465 * If data is accessed over XHR via Connection Manager, the connection timeout
466 * defines how many milliseconds the XHR connection will wait for a server
467 * response. Any non-zero value will enable the Connection utility's
468 * Auto-Abort feature.
470 * @property connTimeout
474 YAHOO
.util
.DataSource
.prototype.connTimeout
= 0;
476 /////////////////////////////////////////////////////////////////////////////
478 // Public static methods
480 /////////////////////////////////////////////////////////////////////////////
483 * Converts data to type String.
485 * @method DataSource.parseString
486 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
487 * The special values null and undefined will return null.
488 * @return {Number} A string, or null.
491 YAHOO
.util
.DataSource
.parseString = function(oData
) {
492 // Special case null and undefined
493 if(!YAHOO
.lang
.isValue(oData
)) {
498 var string
= oData
+ "";
501 if(YAHOO
.lang
.isString(string
)) {
505 YAHOO
.log("Could not convert data " + YAHOO
.lang
.dump(oData
) + " to type String", "warn", this.toString());
511 * Converts data to type Number.
513 * @method DataSource.parseNumber
514 * @param oData {String | Number | Boolean | Null} Data to convert. Beware, null
516 * @return {Number} A number, or null if NaN.
519 YAHOO
.util
.DataSource
.parseNumber = function(oData
) {
521 var number
= oData
* 1;
524 if(YAHOO
.lang
.isNumber(number
)) {
528 YAHOO
.log("Could not convert data " + YAHOO
.lang
.dump(oData
) + " to type Number", "warn", this.toString());
532 // Backward compatibility
533 YAHOO
.util
.DataSource
.convertNumber = function(oData
) {
534 YAHOO
.log("The method YAHOO.util.DataSource.convertNumber() has been" +
535 " deprecated in favor of YAHOO.util.DataSource.parseNumber()", "warn",
537 return YAHOO
.util
.DataSource
.parseNumber(oData
);
541 * Converts data to type Date.
543 * @method DataSource.parseDate
544 * @param oData {Date | String | Number} Data to convert.
545 * @return {Date} A Date instance.
548 YAHOO
.util
.DataSource
.parseDate = function(oData
) {
552 if(!(oData
instanceof Date
)) {
553 date
= new Date(oData
);
560 if(date
instanceof Date
) {
564 YAHOO
.log("Could not convert data " + YAHOO
.lang
.dump(oData
) + " to type Date", "warn", this.toString());
568 // Backward compatibility
569 YAHOO
.util
.DataSource
.convertDate = function(oData
) {
570 YAHOO
.log("The method YAHOO.util.DataSource.convertDate() has been" +
571 " deprecated in favor of YAHOO.util.DataSource.parseDate()", "warn",
573 return YAHOO
.util
.DataSource
.parseDate(oData
);
576 /////////////////////////////////////////////////////////////////////////////
580 /////////////////////////////////////////////////////////////////////////////
583 * Public accessor to the unique name of the DataSource instance.
586 * @return {String} Unique name of the DataSource instance.
588 YAHOO
.util
.DataSource
.prototype.toString = function() {
593 * Overridable method passes request to cache and returns cached response if any,
594 * refreshing the hit in the cache as the newest item. Returns null if there is
597 * @method getCachedResponse
598 * @param oRequest {Object} Request object.
599 * @param oCallback {Function} Handler function to receive the response.
600 * @param oCaller {Object} The Calling object that is making the request.
601 * @return {Object} Cached response object or null.
603 YAHOO
.util
.DataSource
.prototype.getCachedResponse = function(oRequest
, oCallback
, oCaller
) {
604 var aCache
= this._aCache
;
605 var nCacheLength
= (aCache
) ? aCache
.length
: 0;
606 var oResponse
= null;
608 // If cache is enabled...
609 if((this.maxCacheEntries
> 0) && aCache
&& (nCacheLength
> 0)) {
610 this.fireEvent("cacheRequestEvent", {request
:oRequest
,callback
:oCallback
,caller
:oCaller
});
612 // Loop through each cached element
613 for(var i
= nCacheLength
-1; i
>= 0; i
--) {
614 var oCacheElem
= aCache
[i
];
616 // Defer cache hit logic to a public overridable method
617 if(this.isCacheHit(oRequest
,oCacheElem
.request
)) {
618 // Grab the cached response
619 oResponse
= oCacheElem
.response
;
620 // The cache returned a hit!
621 // Remove element from its original location
624 this.addToCache(oRequest
, oResponse
);
625 this.fireEvent("cacheResponseEvent", {request
:oRequest
,response
:oResponse
,callback
:oCallback
,caller
:oCaller
});
630 YAHOO
.log("The cached response for \"" + YAHOO
.lang
.dump(oRequest
) +
631 "\" is " + YAHOO
.lang
.dump(oResponse
), "info", this.toString());
636 * Default overridable method matches given request to given cached request.
637 * Returns true if is a hit, returns false otherwise. Implementers should
638 * override this method to customize the cache-matching algorithm.
641 * @param oRequest {Object} Request object.
642 * @param oCachedRequest {Object} Cached request object.
643 * @return {Boolean} True if given request matches cached request, false otherwise.
645 YAHOO
.util
.DataSource
.prototype.isCacheHit = function(oRequest
, oCachedRequest
) {
646 return (oRequest
=== oCachedRequest
);
650 * Adds a new item to the cache. If cache is full, evicts the stalest item
651 * before adding the new item.
654 * @param oRequest {Object} Request object.
655 * @param oResponse {Object} Response object to cache.
657 YAHOO
.util
.DataSource
.prototype.addToCache = function(oRequest
, oResponse
) {
658 var aCache
= this._aCache
;
663 //TODO: check for duplicate entries
665 // If the cache is full, make room by removing stalest element (index=0)
666 while(aCache
.length
>= this.maxCacheEntries
) {
670 // Add to cache in the newest position, at the end of the array
671 var oCacheElem
= {request
:oRequest
,response
:oResponse
};
672 aCache
.push(oCacheElem
);
673 this.fireEvent("responseCacheEvent", {request
:oRequest
,response
:oResponse
});
674 YAHOO
.log("Cached the response for \"" + oRequest
+ "\"", "info", this.toString());
682 YAHOO
.util
.DataSource
.prototype.flushCache = function() {
685 this.fireEvent("cacheFlushEvent");
686 YAHOO
.log("Flushed the cache", "info", this.toString());
691 * First looks for cached response, then sends request to live data.
693 * @method sendRequest
694 * @param oRequest {Object} Request object.
695 * @param oCallback {Function} Handler function to receive the response.
696 * @param oCaller {Object} The Calling object that is making the request.
697 * @return {Number} Transaction ID, or null if response found in cache.
699 YAHOO
.util
.DataSource
.prototype.sendRequest = function(oRequest
, oCallback
, oCaller
) {
700 // First look in cache
701 var oCachedResponse
= this.getCachedResponse(oRequest
, oCallback
, oCaller
);
702 if(oCachedResponse
) {
703 oCallback
.call(oCaller
, oRequest
, oCachedResponse
);
707 // Not in cache, so forward request to live data
708 YAHOO
.log("Making connection to live data for \"" + oRequest
+ "\"", "info", this.toString());
709 return this.makeConnection(oRequest
, oCallback
, oCaller
);
713 * Overridable method provides default functionality to make a connection to
714 * live data in order to send request. The response coming back is then
715 * forwarded to the handleResponse function. This method should be customized
716 * to achieve more complex implementations.
718 * @method makeConnection
719 * @param oRequest {Object} Request object.
720 * @param oCallback {Function} Handler function to receive the response.
721 * @param oCaller {Object} The Calling object that is making the request.
722 * @return {Number} Transaction ID.
724 YAHOO
.util
.DataSource
.prototype.makeConnection = function(oRequest
, oCallback
, oCaller
) {
725 this.fireEvent("requestEvent", {request
:oRequest
,callback
:oCallback
,caller
:oCaller
});
726 var oRawResponse
= null;
727 var tId
= YAHOO
.util
.DataSource
._nTransactionId
++;
729 // How to make the connection depends on the type of data
730 switch(this.dataType
) {
731 // If the live data is a JavaScript Function
732 // pass the request in as a parameter and
733 // forward the return value to the handler
734 case YAHOO
.util
.DataSource
.TYPE_JSFUNCTION
:
735 oRawResponse
= this.liveData(oRequest
);
736 this.handleResponse(oRequest
, oRawResponse
, oCallback
, oCaller
, tId
);
738 // If the live data is over Connection Manager
739 // set up the callback object and
740 // pass the request in as a URL query and
741 // forward the response to the handler
742 case YAHOO
.util
.DataSource
.TYPE_XHR
:
744 var oConnMgr
= this.connMgr
|| YAHOO
.util
.Connect
;
745 var oQueue
= this._oQueue
;
748 * Define Connection Manager success handler
750 * @method _xhrSuccess
751 * @param oResponse {Object} HTTPXMLRequest object
754 var _xhrSuccess = function(oResponse
) {
755 // If response ID does not match last made request ID,
756 // silently fail and wait for the next response
757 if(oResponse
&& (this.connXhrMode
== "ignoreStaleResponses") &&
758 (oResponse
.tId
!= oQueue
.conn
.tId
)) {
759 YAHOO
.log("Ignored stale response", "warn", this.toString());
762 // Error if no response
763 else if(!oResponse
) {
764 this.fireEvent("dataErrorEvent", {request
:oRequest
,
765 callback
:oCallback
, caller
:oCaller
,
766 message
:YAHOO
.util
.DataSource
.ERROR_DATANULL
});
767 YAHOO
.log(YAHOO
.util
.DataSource
.ERROR_DATANULL
, "error", this.toString());
769 // Send error response back to the caller with the error flag on
770 oCallback
.call(oCaller
, oRequest
, oResponse
, true);
774 // Forward to handler
776 this.handleResponse(oRequest
, oResponse
, oCallback
, oCaller
, tId
);
781 * Define Connection Manager failure handler
783 * @method _xhrFailure
784 * @param oResponse {Object} HTTPXMLRequest object
787 var _xhrFailure = function(oResponse
) {
788 this.fireEvent("dataErrorEvent", {request
:oRequest
,
789 callback
:oCallback
, caller
:oCaller
,
790 message
:YAHOO
.util
.DataSource
.ERROR_DATAINVALID
});
791 YAHOO
.log(YAHOO
.util
.DataSource
.ERROR_DATAINVALID
+ ": " +
792 oResponse
.statusText
, "error", this.toString());
794 // Backward compatibility
795 if((this.liveData
.lastIndexOf("?") !== this.liveData
.length
-1) &&
796 (oRequest
.indexOf("?") !== 0)){
797 YAHOO
.log("DataSources using XHR no longer supply a \"?\"" +
798 " between the host and query parameters" +
799 " -- please check that the request URL is correct", "warn", this.toString());
802 // Send failure response back to the caller with the error flag on
803 oCallback
.call(oCaller
, oRequest
, oResponse
, true);
808 * Define Connection Manager callback object
810 * @property _xhrCallback
811 * @param oResponse {Object} HTTPXMLRequest object
820 // Apply Connection Manager timeout
821 if(YAHOO
.lang
.isNumber(this.connTimeout
)) {
822 _xhrCallback
.timeout
= this.connTimeout
;
825 // Cancel stale requests
826 if(this.connXhrMode
== "cancelStaleRequests") {
827 // Look in queue for stale requests
830 oConnMgr
.abort(oQueue
.conn
);
832 YAHOO
.log("Canceled stale request", "warn", this.toString());
835 YAHOO
.log("Could not find Connection Manager abort() function", "error", this.toString());
840 // Get ready to send the request URL
841 if(oConnMgr
&& oConnMgr
.asyncRequest
) {
842 var sLiveData
= this.liveData
;
843 var isPost
= this.connMethodPost
;
844 var sMethod
= (isPost
) ? "POST" : "GET";
845 var sUri
= (isPost
) ? sLiveData
: sLiveData
+oRequest
;
846 var sRequest
= (isPost
) ? oRequest
: null;
848 // Send the request right away
849 if(this.connXhrMode
!= "queueRequests") {
850 oQueue
.conn
= oConnMgr
.asyncRequest(sMethod
, sUri
, _xhrCallback
, sRequest
);
852 // Queue up then send the request
854 // Found a request already in progress
856 // Add request to queue
857 oQueue
.requests
.push({request
:oRequest
, callback
:_xhrCallback
});
859 // Interval needs to be started
860 if(!oQueue
.interval
) {
861 oQueue
.interval
= setInterval(function() {
862 // Connection is in progress
863 if(oConnMgr
.isCallInProgress(oQueue
.conn
)) {
868 if(oQueue
.requests
.length
> 0) {
869 sUri
= (isPost
) ? sLiveData
: sLiveData
+oQueue
.requests
[0].request
;
870 sRequest
= (isPost
) ? oQueue
.requests
[0].request
: null;
871 oQueue
.conn
= oConnMgr
.asyncRequest(sMethod
, sUri
, oQueue
.requests
[0].callback
, sRequest
);
873 // Remove request from queue
874 oQueue
.requests
.shift();
878 clearInterval(oQueue
.interval
);
879 oQueue
.interval
= null;
885 // Nothing is in progress
887 oQueue
.conn
= oConnMgr
.asyncRequest(sMethod
, sUri
, _xhrCallback
, sRequest
);
892 YAHOO
.log("Could not find Connection Manager asyncRequest() function", "error", this.toString());
893 // Send null response back to the caller with the error flag on
894 oCallback
.call(oCaller
, oRequest
, null, true);
898 // Simply forward the entire data object to the handler
900 /* accounts for the following cases:
901 YAHOO.util.DataSource.TYPE_UNKNOWN:
902 YAHOO.util.DataSource.TYPE_JSARRAY:
903 YAHOO.util.DataSource.TYPE_JSON:
904 YAHOO.util.DataSource.TYPE_HTMLTABLE:
905 YAHOO.util.DataSource.TYPE_XML:
907 oRawResponse
= this.liveData
;
908 this.handleResponse(oRequest
, oRawResponse
, oCallback
, oCaller
, tId
);
915 * Handles raw data response from live data source. Sends a parsed response object
916 * to the callback function in this format:
918 * fnCallback(oRequest, oParsedResponse)
920 * where the oParsedResponse object literal with the following properties:
922 * <li>tId {Number} Unique transaction ID</li>
923 * <li>results {Array} Array of parsed data results</li>
924 * <li>error {Boolean} True if there was an error</li>
927 * @method handleResponse
928 * @param oRequest {Object} Request object
929 * @param oRawResponse {Object} The raw response from the live database.
930 * @param oCallback {Function} Handler function to receive the response.
931 * @param oCaller {Object} The calling object that is making the request.
932 * @param tId {Number} Transaction ID.
934 YAHOO
.util
.DataSource
.prototype.handleResponse = function(oRequest
, oRawResponse
, oCallback
, oCaller
, tId
) {
935 this.fireEvent("responseEvent", {request
:oRequest
, response
:oRawResponse
,
936 callback
:oCallback
, caller
:oCaller
, tId
: tId
});
937 YAHOO
.log("Received live data response for \"" + oRequest
+ "\"", "info", this.toString());
938 var xhr
= (this.dataType
== YAHOO
.util
.DataSource
.TYPE_XHR
) ? true : false;
939 var oParsedResponse
= null;
942 // Access to the raw response before it gets parsed
943 oRawResponse
= this.doBeforeParseData(oRequest
, oRawResponse
);
945 switch(this.responseType
) {
946 case YAHOO
.util
.DataSource
.TYPE_JSARRAY
:
947 if(xhr
&& oRawResponse
.responseText
) {
948 oRawResponse
= oRawResponse
.responseText
;
950 oParsedResponse
= this.parseArrayData(oRequest
, oRawResponse
);
952 case YAHOO
.util
.DataSource
.TYPE_JSON
:
953 if(xhr
&& oRawResponse
.responseText
) {
954 oRawResponse
= oRawResponse
.responseText
;
956 oParsedResponse
= this.parseJSONData(oRequest
, oRawResponse
);
958 case YAHOO
.util
.DataSource
.TYPE_HTMLTABLE
:
959 if(xhr
&& oRawResponse
.responseText
) {
960 oRawResponse
= oRawResponse
.responseText
;
962 oParsedResponse
= this.parseHTMLTableData(oRequest
, oRawResponse
);
964 case YAHOO
.util
.DataSource
.TYPE_XML
:
965 if(xhr
&& oRawResponse
.responseXML
) {
966 oRawResponse
= oRawResponse
.responseXML
;
968 oParsedResponse
= this.parseXMLData(oRequest
, oRawResponse
);
970 case YAHOO
.util
.DataSource
.TYPE_TEXT
:
971 if(xhr
&& oRawResponse
.responseText
) {
972 oRawResponse
= oRawResponse
.responseText
;
974 oParsedResponse
= this.parseTextData(oRequest
, oRawResponse
);
977 //var contentType = oRawResponse.getResponseHeader["Content-Type"];
978 YAHOO
.log("Could not parse data for request \"" + oRequest
+
979 "\" due to unknown response type", "error", this.toString());
984 if(oParsedResponse
) {
985 // Last chance to touch the raw response or the parsed response
986 oParsedResponse
.tId
= tId
;
987 oParsedResponse
= this.doBeforeCallback(oRequest
, oRawResponse
, oParsedResponse
);
988 this.fireEvent("responseParseEvent", {request
:oRequest
,
989 response
:oParsedResponse
, callback
:oCallback
, caller
:oCaller
});
990 // Cache the response
991 this.addToCache(oRequest
, oParsedResponse
);
994 this.fireEvent("dataErrorEvent", {request
:oRequest
, callback
:oCallback
,
995 caller
:oCaller
, message
:YAHOO
.util
.DataSource
.ERROR_DATANULL
});
996 YAHOO
.log(YAHOO
.util
.DataSource
.ERROR_DATANULL
, "error", this.toString());
998 // Send response back to the caller with the error flag on
999 oParsedResponse
= {error
:true};
1002 // Send the response back to the caller
1003 oCallback
.call(oCaller
, oRequest
, oParsedResponse
);
1007 * Overridable method gives implementers access to the original raw response
1008 * before the data gets parsed. Implementers should take care not to return an
1009 * unparsable or otherwise invalid raw response.
1011 * @method doBeforeParseData
1012 * @param oRequest {Object} Request object.
1013 * @param oRawResponse {Object} The raw response from the live database.
1014 * @return {Object} Raw response for parsing.
1016 YAHOO
.util
.DataSource
.prototype.doBeforeParseData = function(oRequest
, oRawResponse
) {
1017 return oRawResponse
;
1021 * Overridable method gives implementers access to the original raw response and
1022 * the parsed response (parsed against the given schema) before the data
1023 * is added to the cache (if applicable) and then sent back to callback function.
1024 * This is your chance to access the raw response and/or populate the parsed
1025 * response with any custom data.
1027 * @method doBeforeCallback
1028 * @param oRequest {Object} Request object.
1029 * @param oRawResponse {Object} The raw response from the live database.
1030 * @param oParsedResponse {Object} The parsed response to return to calling object.
1031 * @return {Object} Parsed response object.
1033 YAHOO
.util
.DataSource
.prototype.doBeforeCallback = function(oRequest
, oRawResponse
, oParsedResponse
) {
1034 return oParsedResponse
;
1038 * Overridable method parses raw array data into a response object.
1040 * @method parseArrayData
1041 * @param oRequest {Object} Request object.
1042 * @param oRawResponse {Object} The raw response from the live database.
1043 * @return {Object} Parsed response object.
1045 YAHOO
.util
.DataSource
.prototype.parseArrayData = function(oRequest
, oRawResponse
) {
1046 if(YAHOO
.lang
.isArray(oRawResponse
) && YAHOO
.lang
.isArray(this.responseSchema
.fields
)) {
1047 var oParsedResponse
= {results
:[]};
1048 var fields
= this.responseSchema
.fields
;
1049 for(var i
=oRawResponse
.length
-1; i
>-1; i
--) {
1051 for(var j
=fields
.length
-1; j
>-1; j
--) {
1052 var field
= fields
[j
];
1053 var key
= (YAHOO
.lang
.isValue(field
.key
)) ? field
.key
: field
;
1054 var data
= (YAHOO
.lang
.isValue(oRawResponse
[i
][j
])) ? oRawResponse
[i
][j
] : oRawResponse
[i
][key
];
1055 // Backward compatibility
1056 if(!field
.parser
&& field
.converter
) {
1057 field
.parser
= field
.converter
;
1058 YAHOO
.log("The field property converter has been deprecated" +
1059 " in favor of parser", "warn", this.toString());
1062 data
= field
.parser
.call(this, data
);
1065 if(data
=== undefined) {
1068 oResult
[key
] = data
;
1070 oParsedResponse
.results
.unshift(oResult
);
1072 YAHOO
.log("Parsed array data is " +
1073 YAHOO
.lang
.dump(oParsedResponse
), "info", this.toString());
1074 return oParsedResponse
;
1077 YAHOO
.log("Array data could not be parsed: " +
1078 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1084 * Overridable method parses raw plain text data into a response object.
1086 * @method parseTextData
1087 * @param oRequest {Object} Request object.
1088 * @param oRawResponse {Object} The raw response from the live database.
1089 * @return {Object} Parsed response object.
1091 YAHOO
.util
.DataSource
.prototype.parseTextData = function(oRequest
, oRawResponse
) {
1092 var oParsedResponse
= {};
1093 if(YAHOO
.lang
.isString(oRawResponse
) &&
1094 YAHOO
.lang
.isArray(this.responseSchema
.fields
) &&
1095 YAHOO
.lang
.isString(this.responseSchema
.recordDelim
) &&
1096 YAHOO
.lang
.isString(this.responseSchema
.fieldDelim
)) {
1097 oParsedResponse
.results
= [];
1098 var recDelim
= this.responseSchema
.recordDelim
;
1099 var fieldDelim
= this.responseSchema
.fieldDelim
;
1100 var fields
= this.responseSchema
.fields
;
1101 if(oRawResponse
.length
> 0) {
1102 // Delete the last line delimiter at the end of the data if it exists
1103 var newLength
= oRawResponse
.length
-recDelim
.length
;
1104 if(oRawResponse
.substr(newLength
) == recDelim
) {
1105 oRawResponse
= oRawResponse
.substr(0, newLength
);
1107 // Split along record delimiter to get an array of strings
1108 var recordsarray
= oRawResponse
.split(recDelim
);
1109 // Cycle through each record, except the first which contains header info
1110 for(var i
= recordsarray
.length
-1; i
>-1; i
--) {
1112 for(var j
=fields
.length
-1; j
>-1; j
--) {
1113 // Split along field delimter to get each data value
1114 var fielddataarray
= recordsarray
[i
].split(fieldDelim
);
1116 // Remove quotation marks from edges, if applicable
1117 var data
= fielddataarray
[j
];
1118 if(data
.charAt(0) == "\"") {
1119 data
= data
.substr(1);
1121 if(data
.charAt(data
.length
-1) == "\"") {
1122 data
= data
.substr(0,data
.length
-1);
1124 var field
= fields
[j
];
1125 var key
= (YAHOO
.lang
.isValue(field
.key
)) ? field
.key
: field
;
1126 // Backward compatibility
1127 if(!field
.parser
&& field
.converter
) {
1128 field
.parser
= field
.converter
;
1129 YAHOO
.log("The field property converter has been deprecated" +
1130 " in favor of parser", "warn", this.toString());
1133 data
= field
.parser
.call(this, data
);
1136 if(data
=== undefined) {
1139 oResult
[key
] = data
;
1141 oParsedResponse
.results
.unshift(oResult
);
1144 YAHOO
.log("Parsed text data is " +
1145 YAHOO
.lang
.dump(oParsedResponse
), "info", this.toString());
1148 YAHOO
.log("Text data could not be parsed: " +
1149 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1150 oParsedResponse
.error
= true;
1152 return oParsedResponse
;
1156 * Overridable method parses raw XML data into a response object.
1158 * @method parseXMLData
1159 * @param oRequest {Object} Request object.
1160 * @param oRawResponse {Object} The raw response from the live database.
1161 * @return {Object} Parsed response object.
1163 YAHOO
.util
.DataSource
.prototype.parseXMLData = function(oRequest
, oRawResponse
) {
1165 var oParsedResponse
= {};
1166 var xmlList
= (this.responseSchema
.resultNode
) ?
1167 oRawResponse
.getElementsByTagName(this.responseSchema
.resultNode
) :
1169 if(!xmlList
|| !YAHOO
.lang
.isArray(this.responseSchema
.fields
)) {
1172 // Loop through each result
1174 oParsedResponse
.results
= [];
1175 for(var k
= xmlList
.length
-1; k
>= 0 ; k
--) {
1176 var result
= xmlList
.item(k
);
1178 // Loop through each data field in each result using the schema
1179 for(var m
= this.responseSchema
.fields
.length
-1; m
>= 0 ; m
--) {
1180 var field
= this.responseSchema
.fields
[m
];
1181 var key
= (YAHOO
.lang
.isValue(field
.key
)) ? field
.key
: field
;
1183 // Values may be held in an attribute...
1184 var xmlAttr
= result
.attributes
.getNamedItem(key
);
1186 data
= xmlAttr
.value
;
1190 var xmlNode
= result
.getElementsByTagName(key
);
1191 if(xmlNode
&& xmlNode
.item(0) && xmlNode
.item(0).firstChild
) {
1192 data
= xmlNode
.item(0).firstChild
.nodeValue
;
1198 // Backward compatibility
1199 if(!field
.parser
&& field
.converter
) {
1200 field
.parser
= field
.converter
;
1201 YAHOO
.log("The field property converter has been deprecated" +
1202 " in favor of parser", "warn", this.toString());
1205 data
= field
.parser
.call(this, data
);
1208 if(data
=== undefined) {
1211 oResult
[key
] = data
;
1213 // Capture each array of values into an array of results
1214 oParsedResponse
.results
.unshift(oResult
);
1218 YAHOO
.log("XML data could not be parsed: " +
1219 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1220 oParsedResponse
.error
= true;
1223 YAHOO
.log("Parsed XML data is " +
1224 YAHOO
.lang
.dump(oParsedResponse
), "info", this.toString());
1226 return oParsedResponse
;
1230 * Overridable method parses raw JSON data into a response object.
1232 * @method parseJSONData
1233 * @param oRequest {Object} Request object.
1234 * @param oRawResponse {Object} The raw response from the live database.
1235 * @return {Object} Parsed response object.
1237 YAHOO
.util
.DataSource
.prototype.parseJSONData = function(oRequest
, oRawResponse
) {
1238 var oParsedResponse
= {};
1239 if(oRawResponse
&& YAHOO
.lang
.isArray(this.responseSchema
.fields
)) {
1240 var fields
= this.responseSchema
.fields
;
1242 oParsedResponse
.results
= [];
1243 var jsonObj
,jsonList
;
1245 // Parse JSON object out if it's a string
1246 if(YAHOO
.lang
.isString(oRawResponse
)) {
1247 // Check for latest JSON lib but divert KHTML clients
1248 var isNotMac
= (navigator
.userAgent
.toLowerCase().indexOf('khtml')== -1);
1249 if(oRawResponse
.parseJSON
&& isNotMac
) {
1250 // Use the new JSON utility if available
1251 jsonObj
= oRawResponse
.parseJSON();
1256 // Check for older JSON lib but divert KHTML clients
1257 else if(window
.JSON
&& JSON
.parse
&& isNotMac
) {
1258 // Use the JSON utility if available
1259 jsonObj
= JSON
.parse(oRawResponse
);
1264 // No JSON lib found so parse the string
1267 // Trim leading spaces
1268 while (oRawResponse
.length
> 0 &&
1269 (oRawResponse
.charAt(0) != "{") &&
1270 (oRawResponse
.charAt(0) != "[")) {
1271 oRawResponse
= oRawResponse
.substring(1, oRawResponse
.length
);
1274 if(oRawResponse
.length
> 0) {
1275 // Strip extraneous stuff at the end
1276 var objEnd
= Math
.max(oRawResponse
.lastIndexOf("]"),oRawResponse
.lastIndexOf("}"));
1277 oRawResponse
= oRawResponse
.substring(0,objEnd
+1);
1279 // Turn the string into an object literal...
1280 // ...eval is necessary here
1281 jsonObj
= eval("(" + oRawResponse
+ ")");
1297 // Response must already be a JSON object
1298 else if(oRawResponse
.constructor == Object
) {
1299 jsonObj
= oRawResponse
;
1301 // Not a string or an object
1305 // Now that we have a JSON object, parse a jsonList out of it
1306 if(jsonObj
&& jsonObj
.constructor == Object
) {
1308 // eval is necessary here since schema can be of unknown depth
1309 jsonList
= eval("jsonObj." + this.responseSchema
.resultsList
);
1316 if(bError
|| !jsonList
) {
1317 YAHOO
.log("JSON data could not be parsed: " +
1318 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1319 oParsedResponse
.error
= true;
1321 if(jsonList
&& !YAHOO
.lang
.isArray(jsonList
)) {
1322 jsonList
= [jsonList
];
1324 else if(!jsonList
) {
1328 // Loop through the array of all responses...
1329 for(var i
= jsonList
.length
-1; i
>= 0 ; i
--) {
1331 var jsonResult
= jsonList
[i
];
1332 // ...and loop through each data field value of each response
1333 for(var j
= fields
.length
-1; j
>= 0 ; j
--) {
1334 var field
= fields
[j
];
1335 var key
= (YAHOO
.lang
.isValue(field
.key
)) ? field
.key
: field
;
1336 // ...and capture data into an array mapped according to the schema...
1337 // eval is necessary here since schema can be of unknown depth
1338 var data
= eval("jsonResult." + key
);
1339 //YAHOO.log("data: " + i + " value:" +j+" = "+dataFieldValue,"debug",this.toString());
1341 // Backward compatibility
1342 if(!field
.parser
&& field
.converter
) {
1343 field
.parser
= field
.converter
;
1344 YAHOO
.log("The field property converter has been deprecated" +
1345 " in favor of parser", "warn", this.toString());
1348 data
= field
.parser
.call(this, data
);
1351 if(data
=== undefined) {
1354 oResult
[key
] = data
;
1356 // Capture the array of data field values in an array of results
1357 oParsedResponse
.results
.unshift(oResult
);
1359 YAHOO
.log("Parsed JSON data is " +
1360 YAHOO
.lang
.dump(oParsedResponse
), "info", this.toString());
1363 YAHOO
.log("JSON data could not be parsed: " +
1364 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1365 oParsedResponse
.error
= true;
1367 return oParsedResponse
;
1371 * Overridable method parses raw HTML TABLE element data into a response object.
1373 * @method parseHTMLTableData
1374 * @param oRequest {Object} Request object.
1375 * @param oRawResponse {Object} The raw response from the live database.
1376 * @return {Object} Parsed response object.
1378 YAHOO
.util
.DataSource
.prototype.parseHTMLTableData = function(oRequest
, oRawResponse
) {
1380 var elTable
= oRawResponse
;
1381 var fields
= this.responseSchema
.fields
;
1382 var oParsedResponse
= {};
1383 oParsedResponse
.results
= [];
1385 // Iterate through each TBODY
1386 for(var i
=0; i
<elTable
.tBodies
.length
; i
++) {
1387 var elTbody
= elTable
.tBodies
[i
];
1389 // Iterate through each TR
1390 for(var j
=elTbody
.rows
.length
-1; j
>-1; j
--) {
1391 var elRow
= elTbody
.rows
[j
];
1394 for(var k
=fields
.length
-1; k
>-1; k
--) {
1395 var field
= fields
[k
];
1396 var key
= (YAHOO
.lang
.isValue(field
.key
)) ? field
.key
: field
;
1397 var data
= elRow
.cells
[k
].innerHTML
;
1399 // Backward compatibility
1400 if(!field
.parser
&& field
.converter
) {
1401 field
.parser
= field
.converter
;
1402 YAHOO
.log("The field property converter has been deprecated" +
1403 " in favor of parser", "warn", this.toString());
1406 data
= field
.parser
.call(this, data
);
1409 if(data
=== undefined) {
1412 oResult
[key
] = data
;
1414 oParsedResponse
.results
.unshift(oResult
);
1419 YAHOO
.log("HTML TABLE data could not be parsed: " +
1420 YAHOO
.lang
.dump(oRawResponse
), "error", this.toString());
1421 oParsedResponse
.error
= true;
1424 YAHOO
.log("Parsed HTML TABLE data is " +
1425 YAHOO
.lang
.dump(oParsedResponse
), "info", this.toString());
1427 return oParsedResponse
;
1430 YAHOO
.register("datasource", YAHOO
.util
.DataSource
, {version
: "2.3.0", build
: "442"});