This repository has been archived by the owner on Jan 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
yui2-datasource.js
3000 lines (2656 loc) · 100 KB
/
yui2-datasource.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
YUI.add('yui2-datasource', function(Y) {
var YAHOO = Y.YUI2;
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.8.2r1
*/
(function () {
var lang = YAHOO.lang,
util = YAHOO.util,
Ev = util.Event;
/**
* The DataSource utility provides a common configurable interface for widgets to
* access a variety of data, from JavaScript arrays to online database servers.
*
* @module datasource
* @requires yahoo, event
* @optional json, get, connection
* @title DataSource Utility
*/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* Base class for the YUI DataSource utility.
*
* @namespace YAHOO.util
* @class YAHOO.util.DataSourceBase
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.DataSourceBase = function(oLiveData, oConfigs) {
if(oLiveData === null || oLiveData === undefined) {
return;
}
this.liveData = oLiveData;
this._oQueue = {interval:null, conn:null, requests:[]};
this.responseSchema = {};
// Set any config params passed in to override defaults
if(oConfigs && (oConfigs.constructor == Object)) {
for(var sConfig in oConfigs) {
if(sConfig) {
this[sConfig] = oConfigs[sConfig];
}
}
}
// Validate and initialize public configs
var maxCacheEntries = this.maxCacheEntries;
if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
maxCacheEntries = 0;
}
// Initialize interval tracker
this._aIntervals = [];
/////////////////////////////////////////////////////////////////////////////
//
// Custom Events
//
/////////////////////////////////////////////////////////////////////////////
/**
* Fired when a request is made to the local cache.
*
* @event cacheRequestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("cacheRequestEvent");
/**
* Fired when data is retrieved from the local cache.
*
* @event cacheResponseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The response object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("cacheResponseEvent");
/**
* Fired when a request is sent to the live data source.
*
* @event requestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.tId {Number} Transaction ID.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("requestEvent");
/**
* Fired when live data source sends response.
*
* @event responseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The raw response object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.tId {Number} Transaction ID.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("responseEvent");
/**
* Fired when response is parsed.
*
* @event responseParseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("responseParseEvent");
/**
* Fired when response is cached.
*
* @event responseCacheEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Object} The callback object.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
*/
this.createEvent("responseCacheEvent");
/**
* Fired when an error is encountered with the live data source.
*
* @event dataErrorEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {String} The response object (if available).
* @param oArgs.callback {Object} The callback object.
* @param oArgs.caller {Object} (deprecated) Use callback.scope.
* @param oArgs.message {String} The error message.
*/
this.createEvent("dataErrorEvent");
/**
* Fired when the local cache is flushed.
*
* @event cacheFlushEvent
*/
this.createEvent("cacheFlushEvent");
var DS = util.DataSourceBase;
this._sName = "DataSource instance" + DS._nIndex;
DS._nIndex++;
};
var DS = util.DataSourceBase;
lang.augmentObject(DS, {
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase public constants
//
/////////////////////////////////////////////////////////////////////////////
/**
* Type is unknown.
*
* @property TYPE_UNKNOWN
* @type Number
* @final
* @default -1
*/
TYPE_UNKNOWN : -1,
/**
* Type is a JavaScript Array.
*
* @property TYPE_JSARRAY
* @type Number
* @final
* @default 0
*/
TYPE_JSARRAY : 0,
/**
* Type is a JavaScript Function.
*
* @property TYPE_JSFUNCTION
* @type Number
* @final
* @default 1
*/
TYPE_JSFUNCTION : 1,
/**
* Type is hosted on a server via an XHR connection.
*
* @property TYPE_XHR
* @type Number
* @final
* @default 2
*/
TYPE_XHR : 2,
/**
* Type is JSON.
*
* @property TYPE_JSON
* @type Number
* @final
* @default 3
*/
TYPE_JSON : 3,
/**
* Type is XML.
*
* @property TYPE_XML
* @type Number
* @final
* @default 4
*/
TYPE_XML : 4,
/**
* Type is plain text.
*
* @property TYPE_TEXT
* @type Number
* @final
* @default 5
*/
TYPE_TEXT : 5,
/**
* Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
*
* @property TYPE_HTMLTABLE
* @type Number
* @final
* @default 6
*/
TYPE_HTMLTABLE : 6,
/**
* Type is hosted on a server via a dynamic script node.
*
* @property TYPE_SCRIPTNODE
* @type Number
* @final
* @default 7
*/
TYPE_SCRIPTNODE : 7,
/**
* Type is local.
*
* @property TYPE_LOCAL
* @type Number
* @final
* @default 8
*/
TYPE_LOCAL : 8,
/**
* Error message for invalid dataresponses.
*
* @property ERROR_DATAINVALID
* @type String
* @final
* @default "Invalid data"
*/
ERROR_DATAINVALID : "Invalid data",
/**
* Error message for null data responses.
*
* @property ERROR_DATANULL
* @type String
* @final
* @default "Null data"
*/
ERROR_DATANULL : "Null data",
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase private static properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Internal class variable to index multiple DataSource instances.
*
* @property DataSourceBase._nIndex
* @type Number
* @private
* @static
*/
_nIndex : 0,
/**
* Internal class variable to assign unique transaction IDs.
*
* @property DataSourceBase._nTransactionId
* @type Number
* @private
* @static
*/
_nTransactionId : 0,
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase private static methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Get an XPath-specified value for a given field from an XML node or document.
*
* @method _getLocationValue
* @param field {String | Object} Field definition.
* @param context {Object} XML node or document to search within.
* @return {Object} Data value or null.
* @static
* @private
*/
_getLocationValue: function(field, context) {
var locator = field.locator || field.key || field,
xmldoc = context.ownerDocument || context,
result, res, value = null;
try {
// Standards mode
if(!lang.isUndefined(xmldoc.evaluate)) {
result = xmldoc.evaluate(locator, context, xmldoc.createNSResolver(!context.ownerDocument ? context.documentElement : context.ownerDocument.documentElement), 0, null);
while(res = result.iterateNext()) {
value = res.textContent;
}
}
// IE mode
else {
xmldoc.setProperty("SelectionLanguage", "XPath");
result = context.selectNodes(locator)[0];
value = result.value || result.text || null;
}
return value;
}
catch(e) {
}
},
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase public static methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Executes a configured callback. For object literal callbacks, the third
* param determines whether to execute the success handler or failure handler.
*
* @method issueCallback
* @param callback {Function|Object} the callback to execute
* @param params {Array} params to be passed to the callback method
* @param error {Boolean} whether an error occurred
* @param scope {Object} the scope from which to execute the callback
* (deprecated - use an object literal callback)
* @static
*/
issueCallback : function (callback,params,error,scope) {
if (lang.isFunction(callback)) {
callback.apply(scope, params);
} else if (lang.isObject(callback)) {
scope = callback.scope || scope || window;
var callbackFunc = callback.success;
if (error) {
callbackFunc = callback.failure;
}
if (callbackFunc) {
callbackFunc.apply(scope, params.concat([callback.argument]));
}
}
},
/**
* Converts data to type String.
*
* @method DataSourceBase.parseString
* @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
* The special values null and undefined will return null.
* @return {String} A string, or null.
* @static
*/
parseString : function(oData) {
// Special case null and undefined
if(!lang.isValue(oData)) {
return null;
}
//Convert to string
var string = oData + "";
// Validate
if(lang.isString(string)) {
return string;
}
else {
return null;
}
},
/**
* Converts data to type Number.
*
* @method DataSourceBase.parseNumber
* @param oData {String | Number | Boolean} Data to convert. Note, the following
* values return as null: null, undefined, NaN, "".
* @return {Number} A number, or null.
* @static
*/
parseNumber : function(oData) {
if(!lang.isValue(oData) || (oData === "")) {
return null;
}
//Convert to number
var number = oData * 1;
// Validate
if(lang.isNumber(number)) {
return number;
}
else {
return null;
}
},
// Backward compatibility
convertNumber : function(oData) {
return DS.parseNumber(oData);
},
/**
* Converts data to type Date.
*
* @method DataSourceBase.parseDate
* @param oData {Date | String | Number} Data to convert.
* @return {Date} A Date instance.
* @static
*/
parseDate : function(oData) {
var date = null;
//Convert to date
if(!(oData instanceof Date)) {
date = new Date(oData);
}
else {
return oData;
}
// Validate
if(date instanceof Date) {
return date;
}
else {
return null;
}
},
// Backward compatibility
convertDate : function(oData) {
return DS.parseDate(oData);
}
});
// Done in separate step so referenced functions are defined.
/**
* Data parsing functions.
* @property DataSource.Parser
* @type Object
* @static
*/
DS.Parser = {
string : DS.parseString,
number : DS.parseNumber,
date : DS.parseDate
};
// Prototype properties and methods
DS.prototype = {
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase private properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Name of DataSource instance.
*
* @property _sName
* @type String
* @private
*/
_sName : null,
/**
* Local cache of data result object literals indexed chronologically.
*
* @property _aCache
* @type Object[]
* @private
*/
_aCache : null,
/**
* Local queue of request connections, enabled if queue needs to be managed.
*
* @property _oQueue
* @type Object
* @private
*/
_oQueue : null,
/**
* Array of polling interval IDs that have been enabled, needed to clear all intervals.
*
* @property _aIntervals
* @type Array
* @private
*/
_aIntervals : null,
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* 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.
*
* @property maxCacheEntries
* @type Number
* @default 0
*/
maxCacheEntries : 0,
/**
* Pointer to live database.
*
* @property liveData
* @type Object
*/
liveData : null,
/**
* Where the live data is held:
*
* <dl>
* <dt>TYPE_UNKNOWN</dt>
* <dt>TYPE_LOCAL</dt>
* <dt>TYPE_XHR</dt>
* <dt>TYPE_SCRIPTNODE</dt>
* <dt>TYPE_JSFUNCTION</dt>
* </dl>
*
* @property dataType
* @type Number
* @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
*
*/
dataType : DS.TYPE_UNKNOWN,
/**
* Format of response:
*
* <dl>
* <dt>TYPE_UNKNOWN</dt>
* <dt>TYPE_JSARRAY</dt>
* <dt>TYPE_JSON</dt>
* <dt>TYPE_XML</dt>
* <dt>TYPE_TEXT</dt>
* <dt>TYPE_HTMLTABLE</dt>
* </dl>
*
* @property responseType
* @type Number
* @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
*/
responseType : DS.TYPE_UNKNOWN,
/**
* Response schema object literal takes a combination of the following properties:
*
* <dl>
* <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
* <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
* <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
* <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
* <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
* such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
* <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
* <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
* </dl>
*
* @property responseSchema
* @type Object
*/
responseSchema : null,
/**
* Additional arguments passed to the JSON parse routine. The JSON string
* is the assumed first argument (where applicable). This property is not
* set by default, but the parse methods will use it if present.
*
* @property parseJSONArgs
* @type {MIXED|Array} If an Array, contents are used as individual arguments.
* Otherwise, value is used as an additional argument.
*/
// property intentionally undefined
/**
* When working with XML data, setting this property to true enables support for
* XPath-syntaxed locators in schema definitions.
*
* @property useXPath
* @type Boolean
* @default false
*/
useXPath : false,
/////////////////////////////////////////////////////////////////////////////
//
// DataSourceBase public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Public accessor to the unique name of the DataSource instance.
*
* @method toString
* @return {String} Unique name of the DataSource instance.
*/
toString : function() {
return this._sName;
},
/**
* 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.
*
* @method getCachedResponse
* @param oRequest {Object} Request object.
* @param oCallback {Object} Callback object.
* @param oCaller {Object} (deprecated) Use callback object.
* @return {Object} Cached response object or null.
*/
getCachedResponse : function(oRequest, oCallback, oCaller) {
var aCache = this._aCache;
// If cache is enabled...
if(this.maxCacheEntries > 0) {
// Initialize local cache
if(!aCache) {
this._aCache = [];
}
// Look in local cache
else {
var nCacheLength = aCache.length;
if(nCacheLength > 0) {
var oResponse = null;
this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
// Loop through each cached element
for(var i = nCacheLength-1; i >= 0; i--) {
var oCacheElem = aCache[i];
// Defer cache hit logic to a public overridable method
if(this.isCacheHit(oRequest,oCacheElem.request)) {
// The cache returned a hit!
// Grab the cached response
oResponse = oCacheElem.response;
this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
// Refresh the position of the cache hit
if(i < nCacheLength-1) {
// Remove element from its original location
aCache.splice(i,1);
// Add as newest
this.addToCache(oRequest, oResponse);
}
// Add a cache flag
oResponse.cached = true;
break;
}
}
return oResponse;
}
}
}
else if(aCache) {
this._aCache = null;
}
return null;
},
/**
* 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.
*
* @method isCacheHit
* @param oRequest {Object} Request object.
* @param oCachedRequest {Object} Cached request object.
* @return {Boolean} True if given request matches cached request, false otherwise.
*/
isCacheHit : function(oRequest, oCachedRequest) {
return (oRequest === oCachedRequest);
},
/**
* Adds a new item to the cache. If cache is full, evicts the stalest item
* before adding the new item.
*
* @method addToCache
* @param oRequest {Object} Request object.
* @param oResponse {Object} Response object to cache.
*/
addToCache : function(oRequest, oResponse) {
var aCache = this._aCache;
if(!aCache) {
return;
}
// If the cache is full, make room by removing stalest element (index=0)
while(aCache.length >= this.maxCacheEntries) {
aCache.shift();
}
// Add to cache in the newest position, at the end of the array
var oCacheElem = {request:oRequest,response:oResponse};
aCache[aCache.length] = oCacheElem;
this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
},
/**
* Flushes cache.
*
* @method flushCache
*/
flushCache : function() {
if(this._aCache) {
this._aCache = [];
this.fireEvent("cacheFlushEvent");
}
},
/**
* Sets up a polling mechanism to send requests at set intervals and forward
* responses to given callback.
*
* @method setInterval
* @param nMsec {Number} Length of interval in milliseconds.
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response.
* @param oCaller {Object} (deprecated) Use oCallback.scope.
* @return {Number} Interval ID.
*/
setInterval : function(nMsec, oRequest, oCallback, oCaller) {
if(lang.isNumber(nMsec) && (nMsec >= 0)) {
var oSelf = this;
var nId = setInterval(function() {
oSelf.makeConnection(oRequest, oCallback, oCaller);
}, nMsec);
this._aIntervals.push(nId);
return nId;
}
else {
}
},
/**
* Disables polling mechanism associated with the given interval ID.
*
* @method clearInterval
* @param nId {Number} Interval ID.
*/
clearInterval : function(nId) {
// Remove from tracker if there
var tracker = this._aIntervals || [];
for(var i=tracker.length-1; i>-1; i--) {
if(tracker[i] === nId) {
tracker.splice(i,1);
clearInterval(nId);
}
}
},
/**
* Disables all known polling intervals.
*
* @method clearAllIntervals
*/
clearAllIntervals : function() {
var tracker = this._aIntervals || [];
for(var i=tracker.length-1; i>-1; i--) {
clearInterval(tracker[i]);
}
tracker = [];
},
/**
* First looks for cached response, then sends request to live data. The
* following arguments are passed to the callback function:
* <dl>
* <dt><code>oRequest</code></dt>
* <dd>The same value that was passed in as the first argument to sendRequest.</dd>
* <dt><code>oParsedResponse</code></dt>
* <dd>An object literal containing the following properties:
* <dl>
* <dt><code>tId</code></dt>
* <dd>Unique transaction ID number.</dd>
* <dt><code>results</code></dt>
* <dd>Schema-parsed data results.</dd>
* <dt><code>error</code></dt>
* <dd>True in cases of data error.</dd>
* <dt><code>cached</code></dt>
* <dd>True when response is returned from DataSource cache.</dd>
* <dt><code>meta</code></dt>
* <dd>Schema-parsed meta data.</dd>
* </dl>
* <dt><code>oPayload</code></dt>
* <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
* </dl>
*
* @method sendRequest
* @param oRequest {Object} Request object.
* @param oCallback {Object} An object literal with the following properties:
* <dl>
* <dt><code>success</code></dt>
* <dd>The function to call when the data is ready.</dd>
* <dt><code>failure</code></dt>
* <dd>The function to call upon a response failure condition.</dd>
* <dt><code>scope</code></dt>
* <dd>The object to serve as the scope for the success and failure handlers.</dd>
* <dt><code>argument</code></dt>
* <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
* </dl>
* @param oCaller {Object} (deprecated) Use oCallback.scope.
* @return {Number} Transaction ID, or null if response found in cache.
*/
sendRequest : function(oRequest, oCallback, oCaller) {
// First look in cache
var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
if(oCachedResponse) {
DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
return null;
}
// Not in cache, so forward request to live data
return this.makeConnection(oRequest, oCallback, oCaller);
},
/**
* Overridable default method generates a unique transaction ID and passes
* the live data reference directly to the handleResponse function. This
* method should be implemented by subclasses to achieve more complex behavior
* or to access remote data.
*
* @method makeConnection
* @param oRequest {Object} Request object.
* @param oCallback {Object} Callback object literal.
* @param oCaller {Object} (deprecated) Use oCallback.scope.
* @return {Number} Transaction ID.
*/
makeConnection : function(oRequest, oCallback, oCaller) {
var tId = DS._nTransactionId++;
this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
/* accounts for the following cases:
YAHOO.util.DataSourceBase.TYPE_UNKNOWN
YAHOO.util.DataSourceBase.TYPE_JSARRAY
YAHOO.util.DataSourceBase.TYPE_JSON
YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
YAHOO.util.DataSourceBase.TYPE_XML
YAHOO.util.DataSourceBase.TYPE_TEXT
*/
var oRawResponse = this.liveData;
this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
return 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:
* <dl>
* <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
* <dd><dt>results {Array}</dt> Array of parsed data results</dd>
* <dd><dt>meta {Object}</dt> Object literal of meta values</dd>
* <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
* <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
* </dl>
*
* @method handleResponse
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database.
* @param oCallback {Object} Callback object literal.
* @param oCaller {Object} (deprecated) Use oCallback.scope.
* @param tId {Number} Transaction ID.
*/
handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
callback:oCallback, caller:oCaller});
var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
var oParsedResponse = null;
var oFullResponse = oRawResponse;
// Try to sniff data type if it has not been defined
if(this.responseType === DS.TYPE_UNKNOWN) {
var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
if(ctype) {
// xml
if(ctype.indexOf("text/xml") > -1) {
this.responseType = DS.TYPE_XML;
}
else if(ctype.indexOf("application/json") > -1) { // json
this.responseType = DS.TYPE_JSON;
}
else if(ctype.indexOf("text/plain") > -1) { // text
this.responseType = DS.TYPE_TEXT;
}
}
else {
if(YAHOO.lang.isArray(oRawResponse)) { // array
this.responseType = DS.TYPE_JSARRAY;
}
// xml
else if(oRawResponse && oRawResponse.nodeType && (oRawResponse.nodeType === 9 || oRawResponse.nodeType === 1 || oRawResponse.nodeType === 11)) {
this.responseType = DS.TYPE_XML;
}
else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
this.responseType = DS.TYPE_HTMLTABLE;
}
else if(YAHOO.lang.isObject(oRawResponse)) { // json
this.responseType = DS.TYPE_JSON;
}
else if(YAHOO.lang.isString(oRawResponse)) { // text
this.responseType = DS.TYPE_TEXT;
}
}
}
switch(this.responseType) {
case DS.TYPE_JSARRAY:
if(xhr && oRawResponse && oRawResponse.responseText) {
oFullResponse = oRawResponse.responseText;
}
try {
// Convert to JS array if it's a string
if(lang.isString(oFullResponse)) {
var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
// Check for YUI JSON Util
if(lang.JSON) {
oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
}
// Look for JSON parsers using an API similar to json2.js
else if(window.JSON && JSON.parse) {
oFullResponse = JSON.parse.apply(JSON,parseArgs);
}
// Look for JSON parsers using an API similar to json.js
else if(oFullResponse.parseJSON) {
oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
}
// No JSON lib found so parse the string
else {
// Trim leading spaces
while (oFullResponse.length > 0 &&
(oFullResponse.charAt(0) != "{") &&
(oFullResponse.charAt(0) != "[")) {
oFullResponse = oFullResponse.substring(1, oFullResponse.length);
}