# Yahoo! UI Library

### DataSource Utility 2.5.2

Yahoo! UI Library > datasource > YAHOO.util.DataSource

Show Private Show Protected

## Class YAHOO.util.DataSource - uses YAHOO.util.EventProvider

The DataSource class defines and manages a live set of data for widgets to interact with. Examples of live databases include in-memory local data such as a JavaScript array, a JavaScript function, or JSON, or remote data such as data retrieved through an XHR connection.

### Constructor

YAHOO.util.DataSource `( oLiveData , oConfigs )`

Parameters:
  `oLiveData <Object>` Pointer to live database.
  `oConfigs <Object>` (optional) Object literal of configuration values.

### Properties

#### _aCache `- private Object[]`

Local cache of data result object literals indexed chronologically.

#### _aIntervals `- private Array`

Array of polling interval IDs that have been enabled, needed to clear all intervals.

#### _oQueue `- private Object`

Local queue of request connections, enabled if queue needs to be managed.

#### _sName `- private String`

Name of DataSource instance.

#### _xhrCallback `- private object`

Define Connection Manager callback object

#### connMethodPost `- Boolean`

If data is accessed over XHR via Connection Manager, true if data should be sent via POST, otherwise data will be sent via GET.
Default Value: false

#### connMgr `- Object`

Alias to YUI Connection Manager, to allow implementers to customize the utility.
Default Value: YAHOO.util.Connect

#### connTimeout `- Number`

If data is accessed over XHR via Connection Manager, the connection timeout defines how many milliseconds the XHR connection will wait for a server response. Any non-zero value will enable the Connection utility's Auto-Abort feature.
Default Value: 0

#### connXhrMode `- String`

If data is accessed over XHR via Connection Manager, this setting defines request/response management in the following manner:

queueRequests
  If a request is already in progress, wait until response is returned before sending the next request.
cancelStaleRequests
  If a request is already in progress, cancel it before sending the next request.
ignoreStaleResponses
  Send all requests, but handle only the response for the most recently sent request.
allowAll
  Send all requests and handle all responses.

Default Value: "allowAll"

#### DataSource._nIndex `- private static Number`

Internal class variable to index multiple DataSource instances.

#### DataSource._nTransactionId `- private static Number`

Internal class variable to assign unique transaction IDs.

#### dataType `- Number`

Where the live data is held.
Default Value: YAHOO.util.DataSource.TYPE_UNKNOWN

#### ERROR_DATAINVALID `- final String`

Error message for invalid dataresponses.
Default Value: "Invalid data"

#### ERROR_DATANULL `- final String`

Error message for null data responses.
Default Value: "Null data"

#### liveData `- Object`

Pointer to live database.

#### maxCacheEntries `- Number`

Max size of the local cache. Set to 0 to turn off caching. Caching is useful to reduce the number of server connections. Recommended only for data sources that return comprehensive results for queries or when stale data is not an issue.
Default Value: 0

#### responseSchema `- Object`

Response schema object literal takes a combination of the following properties:

resultsList
  Pointer to array of tabular data
resultNode
  Pointer to node name of row data (XML data only)
recordDelim
  Record delimiter (text data only)
fieldDelim
  Field delimiter (text data only)
fields
  Array of field names (aka keys), or array of object literals such as: {key:"fieldname",parser:YAHOO.util.DataSource.parseDate}
metaFields
  Object literal of keys to include in the oParsedResponse.meta collection
metaNode
  Name of the node under which to search for meta information in XML response data

#### responseType `- Number`

Format of response.
Default Value: YAHOO.util.DataSource.TYPE_UNKNOWN

#### TYPE_HTMLTABLE `- final Number`

Type is an HTML TABLE element.
Default Value: 6

#### TYPE_JSARRAY `- final Number`

Type is a JavaScript Array.
Default Value: 0

#### TYPE_JSFUNCTION `- final Number`

Type is a JavaScript Function.
Default Value: 1

#### TYPE_JSON `- final Number`

Type is JSON.
Default Value: 3

#### TYPE_TEXT `- final Number`

Type is plain text.
Default Value: 5

#### TYPE_UNKNOWN `- final Number`

Type is unknown.
Default Value: -1

#### TYPE_XHR `- final Number`

Type is hosted on a server via an XHR connection.
Default Value: 2

#### TYPE_XML `- final Number`

Type is XML.
Default Value: 4

#### Properties inherited from YAHOO.util.EventProvider:

`__yui_events, __yui_subscribers`

### Methods

#### _xhrFailure

`private void _xhrFailure ( oResponse )`
Define Connection Manager failure handler

Parameters:
  `oResponse <Object>` HTTPXMLRequest object

Returns: `void`

#### _xhrSuccess

`private void _xhrSuccess ( oResponse )`
Define Connection Manager success handler

Parameters:
  `oResponse <Object>` HTTPXMLRequest object

Returns: `void`

#### addToCache

`void addToCache ( oRequest , oResponse )`
Adds a new item to the cache. If cache is full, evicts the stalest item before adding the new item.

Parameters:
  `oRequest <Object>` Request object.
  `oResponse <Object>` Response object to cache.

Returns: `void`

#### clearAllIntervals

`void clearAllIntervals ( )`
Disables all known polling intervals.

Returns: `void`

#### clearInterval

`void clearInterval ( nId )`
Disables polling mechanism associated with the given interval ID.

Parameters:
  `nId <Number>` Interval ID.

Returns: `void`

#### DataSource.parseDate

`static Date DataSource.parseDate ( oData )`
Converts data to type Date.

Parameters:
  `oData <Date | String | Number>` Data to convert.

Returns: `Date`
  A Date instance.

#### DataSource.parseNumber

`static Number DataSource.parseNumber ( oData )`
Converts data to type Number.

Parameters:
  `oData <String | Number | Boolean | Null>` Data to convert. Beware, null returns as 0.

Returns: `Number`
  A number, or null if NaN.

#### DataSource.parseString

`static Number DataSource.parseString ( oData )`
Converts data to type String.

Parameters:
  `oData <String | Number | Boolean | Date | Array | Object>` Data to parse. The special values null and undefined will return null.

Returns: `Number`
  A string, or null.

#### doBeforeCallback

`Object doBeforeCallback ( oRequest , oFullResponse , oParsedResponse )`
Overridable method gives implementers access to the original full response and the parsed response (parsed against the given schema) before the data is added to the cache (if applicable) and then sent back to callback function. This is your chance to access the raw response and/or populate the parsed response with any custom data.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full response from the live database.
  `oParsedResponse <Object>` The parsed response to return to calling object.

Returns: `Object`
  Parsed response object.

#### doBeforeParseData

`Object doBeforeParseData ( oRequest , oFullResponse )`
Overridable method gives implementers access to the original full response before the data gets parsed. Implementers should take care not to return an unparsable or otherwise invalid response.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full response from the live database.

Returns: `Object`
  Full response for parsing.

#### flushCache

`void flushCache ( )`
Flushes cache.

Returns: `void`

#### getCachedResponse

`Object getCachedResponse ( oRequest , oCallback , oCaller )`
Overridable method passes request to cache and returns cached response if any, refreshing the hit in the cache as the newest item. Returns null if there is no cache hit.

Parameters:
  `oRequest <Object>` Request object.
  `oCallback <Function>` Handler function to receive the response.
  `oCaller <Object>` The Calling object that is making the request.

Returns: `Object`
  Cached response object or null.

#### handleResponse

`void handleResponse ( oRequest , oRawResponse , oCallback , oCaller , tId )`
Receives raw data response and type converts to XML, JSON, etc as necessary. Forwards oFullResponse to appropriate parsing function to get turned into oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to the cache when appropriate before calling issueCallback(). The oParsedResponse object literal has the following properties:

tId {Number}
Unique transaction ID
results {Array}
Array of parsed data results
error {Boolean}
True if there was an error
totalRecords {Number}
Total number of records (if available)

Parameters:
  `oRequest <Object>` Request object
  `oRawResponse <Object>` The raw response from the live database.
  `oCallback <Object>` Callback object literal.
  `oCaller <Object>` (deprecated) Use oCallback.scope.
  `tId <Number>` Transaction ID.

Returns: `void`

#### isCacheHit

`Boolean isCacheHit ( oRequest , oCachedRequest )`
Default overridable method matches given request to given cached request. Returns true if is a hit, returns false otherwise. Implementers should override this method to customize the cache-matching algorithm.

Parameters:
  `oRequest <Object>` Request object.
  `oCachedRequest <Object>` Cached request object.

Returns: `Boolean`
  True if given request matches cached request, false otherwise.

#### issueCallback

`void issueCallback ( callback , params , error , scope )`
Executes a configured callback. For object literal callbacks, the third param determines whether to execute the success handler or failure handler.

Parameters:
  `callback <Function|Object>` the callback to execute
  `params <Array>` params to be passed to the callback method
  `error <Boolean>` whether an error occurred
  `scope <Object>` the scope from which to execute the callback (deprecated - use an object literal callback)

Returns: `void`

#### makeConnection

`Number makeConnection ( oRequest , oCallback , oCaller )`
Overridable method provides default functionality to make a connection to live data in order to send request. The response coming back is then forwarded to the handleResponse function. This method should be customized to achieve more complex implementations.

Parameters:
  `oRequest <Object>` Request object.
  `oCallback <Object>` Callback object literal.
  `oCaller <Object>` (deprecated) Use oCallback.scope.

Returns: `Number`
  Transaction ID.

#### parseArrayData

`Object parseArrayData ( oRequest , oFullResponse )`
Overridable method parses Array data into a response object.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full Array from the live database.

Returns: `Object`
  Parsed response object with the following properties:
  - results (Array) Array of parsed data results
  - error (Boolean) True if there was an error
  - totalRecords (Number) Total number of records (if available)

#### parseHTMLTableData

`Object parseHTMLTableData ( oRequest , oFullResponse )`
Overridable method parses an HTML TABLE element reference into a response object.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full HTML element reference from the live database.

Returns: `Object`
  Parsed response object with the following properties
  - results (Array) Array of parsed data results
  - error (Boolean) True if there was an error
  - totalRecords (Number) Total number of records (if available)

#### parseJSONData

`Object parseJSONData ( oRequest , oFullResponse )`
Overridable method parses JSON data into a response object.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full JSON from the live database.

Returns: `Object`
  Parsed response object with the following properties
  - results (Array) Array of parsed data results
  - error (Boolean) True if there was an error
  - totalRecords (Number) Total number of records (if available)

#### parseTextData

`Object parseTextData ( oRequest , oFullResponse )`
Overridable method parses plain text data into a response object.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full text response from the live database.

Returns: `Object`
  Parsed response object with the following properties:
  - results (Array) Array of parsed data results
  - error (Boolean) True if there was an error
  - totalRecords (Number) Total number of records (if available)

#### parseXMLData

`Object parseXMLData ( oRequest , oFullResponse )`
Overridable method parses XML data into a response object.

Parameters:
  `oRequest <Object>` Request object.
  `oFullResponse <Object>` The full XML response from the live database.

Returns: `Object`
  Parsed response object with the following properties
  - results (Array) Array of parsed data results
  - error (Boolean) True if there was an error
  - totalRecords (Number) Total number of records (if available)

#### sendRequest

`Number sendRequest ( oRequest , oCallback , oCaller )`
First looks for cached response, then sends request to live data.

Parameters:
  `oRequest <Object>` Request object.
  `oCallback <Object>` An object literal with the following properties:
  `success`
    The function to call when the data is ready.
  `failure`
    The function to call upon a response failure condition.
  `scope`
    The object to serve as the scope for the success and failure handlers.
  `argument`
    Arbitrary data that will be passed back to the success and failure handlers.
  `oCaller <Object>` (deprecated) Use oCallback.scope.

Returns: `Number`
  Transaction ID, or null if response found in cache.

#### setInterval

`Number setInterval ( nMsec , oRequest , oCallback , oCaller )`
Sets up a polling mechanism to send requests at set intervals and forward responses to given callback.

Parameters:
  `nMsec <Number>` Length of interval in milliseconds.
  `oRequest <Object>` Request object.
  `oCallback <Function>` Handler function to receive the response.
  `oCaller <Object>` (deprecated) Use oCallback.scope.

Returns: `Number`
  Interval ID.

#### toString

`String toString ( )`
Public accessor to the unique name of the DataSource instance.

Returns: `String`
  Unique name of the DataSource instance.

#### Methods inherited from YAHOO.util.EventProvider:

`createEvent, fireEvent, hasEvent, subscribe, unsubscribe, unsubscribeAll`

### Events

#### cacheFlushEvent

`cacheFlushEvent ( )`
Fired when the local cache is flushed.

#### cacheRequestEvent

`cacheRequestEvent ( oArgs.request , oArgs.callback , oArgs.caller )`
Fired when a request is made to the local cache.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.

#### cacheResponseEvent

`cacheResponseEvent ( oArgs.request , oArgs.response , oArgs.callback , oArgs.caller , oArgs.tId )`
Fired when data is retrieved from the local cache.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.response <Object>` The response object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.
  `oArgs.tId <Number>` Transaction ID.

#### dataErrorEvent

`dataErrorEvent ( oArgs.request , oArgs.callback , oArgs.caller , oArgs.message )`
Fired when an error is encountered with the live data source.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.
  `oArgs.message <String>` The error message.

#### requestEvent

`requestEvent ( oArgs.request , oArgs.callback , oArgs.caller )`
Fired when a request is sent to the live data source.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.

#### responseCacheEvent

`responseCacheEvent ( oArgs.request , oArgs.response , oArgs.callback , oArgs.caller )`
Fired when response is cached.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.response <Object>` The parsed response object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.

#### responseEvent

`responseEvent ( oArgs.request , oArgs.response , oArgs.callback , oArgs.caller )`
Fired when live data source sends response.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.response <Object>` The raw response object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.

#### responseParseEvent

`responseParseEvent ( oArgs.request , oArgs.response , oArgs.callback , oArgs.caller )`
Fired when response is parsed.

Parameters:
  `oArgs.request <Object>` The request object.
  `oArgs.response <Object>` The parsed response object.
  `oArgs.callback <Function>` The callback function.
  `oArgs.caller <Object>` (deprecated) Use callback.scope.

Copyright © 2007 Yahoo! Inc. All rights reserved.