datasource-debug.js
109 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
(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) {
YAHOO.log("Could not instantiate DataSource due to invalid live database",
"error", this.toString());
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++;
YAHOO.log("DataSource initialized", "info", this.toString());
};
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
//
/////////////////////////////////////////////////////////////////////////////
/**
* Clones object literal or array of object literals.
*
* @method DataSourceBase._cloneObject
* @param o {Object} Object.
* @private
* @static
*/
_cloneObject: function(o) {
if(!lang.isValue(o)) {
return o;
}
var copy = {};
if(Object.prototype.toString.apply(o) === "[object RegExp]") {
copy = o;
}
else if(lang.isFunction(o)) {
copy = o;
}
else if(lang.isArray(o)) {
var array = [];
for(var i=0,len=o.length;i<len;i++) {
array[i] = DS._cloneObject(o[i]);
}
copy = array;
}
else if(lang.isObject(o)) {
for (var x in o){
if(lang.hasOwnProperty(o, x)) {
if(lang.isValue(o[x]) && lang.isObject(o[x]) || lang.isArray(o[x])) {
copy[x] = DS._cloneObject(o[x]);
}
else {
copy[x] = o[x];
}
}
}
}
else {
copy = o;
}
return copy;
},
/**
* 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 {
YAHOO.log("Could not convert data " + lang.dump(oData) + " to type String", "warn", this.toString());
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 {
YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Number", "warn", this.toString());
return null;
}
},
// Backward compatibility
convertNumber : function(oData) {
YAHOO.log("The method YAHOO.util.DataSourceBase.convertNumber() has been" +
" deprecated in favor of YAHOO.util.DataSourceBase.parseNumber()", "warn",
this.toString());
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(lang.isValue(oData) && !(oData instanceof Date)) {
date = new Date(oData);
}
else {
return oData;
}
// Validate
if(date instanceof Date) {
return date;
}
else {
YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Date", "warn", this.toString());
return null;
}
},
// Backward compatibility
convertDate : function(oData) {
YAHOO.log("The method YAHOO.util.DataSourceBase.convertDate() has been" +
" deprecated in favor of YAHOO.util.DataSourceBase.parseDate()", "warn",
this.toString());
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,
/**
* Clones entries before adding to cache.
*
* @property cloneBeforeCaching
* @type Boolean
* @default false
*/
cloneBeforeCaching : 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 = [];
YAHOO.log("Cache initialized", "info", this.toString());
}
// 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);
YAHOO.log("Refreshed cache position of the response for \"" + oRequest + "\"", "info", this.toString());
}
// Add a cache flag
oResponse.cached = true;
break;
}
}
YAHOO.log("The cached response for \"" + lang.dump(oRequest) +
"\" is " + lang.dump(oResponse), "info", this.toString());
return oResponse;
}
}
}
else if(aCache) {
this._aCache = null;
YAHOO.log("Cache destroyed", "info", this.toString());
}
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
oResponse = (this.cloneBeforeCaching) ? DS._cloneObject(oResponse) : oResponse;
var oCacheElem = {request:oRequest,response:oResponse};
aCache[aCache.length] = oCacheElem;
this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
YAHOO.log("Cached the response for \"" + oRequest + "\"", "info", this.toString());
},
/**
* Flushes cache.
*
* @method flushCache
*/
flushCache : function() {
if(this._aCache) {
this._aCache = [];
this.fireEvent("cacheFlushEvent");
YAHOO.log("Flushed the cache", "info", this.toString());
}
},
/**
* 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)) {
YAHOO.log("Enabling polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
var oSelf = this;
var nId = setInterval(function() {
oSelf.makeConnection(oRequest, oCallback, oCaller);
}, nMsec);
this._aIntervals.push(nId);
return nId;
}
else {
YAHOO.log("Could not enable polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
}
},
/**
* Disables polling mechanism associated with the given interval ID. Does not
* affect transactions that are in progress.
*
* @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. Does not affect transactions that are
* in progress.
*
* @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
YAHOO.log("Making connection to live data for \"" + oRequest + "\"", "info", this.toString());
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});
YAHOO.log("Received live data response for \"" + oRequest + "\"", "info", this.toString());
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);
}
if(oFullResponse.length > 0) {
// Strip extraneous stuff at the end
var arrayEnd =
Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
oFullResponse = oFullResponse.substring(0,arrayEnd+1);
// Turn the string into an object literal...
// ...eval is necessary here
oFullResponse = eval("(" + oFullResponse + ")");
}
}
}
}
catch(e1) {
}
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
break;
case DS.TYPE_JSON:
if(xhr && oRawResponse && oRawResponse.responseText) {
oFullResponse = oRawResponse.responseText;
}
try {
// Convert to JSON object 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);
}
if(oFullResponse.length > 0) {
// Strip extraneous stuff at the end
var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
oFullResponse = oFullResponse.substring(0,objEnd+1);
// Turn the string into an object literal...
// ...eval is necessary here
oFullResponse = eval("(" + oFullResponse + ")");
}
}
}
}
catch(e) {
}
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
break;
case DS.TYPE_HTMLTABLE:
if(xhr && oRawResponse.responseText) {
var el = document.createElement('div');
el.innerHTML = oRawResponse.responseText;
oFullResponse = el.getElementsByTagName('table')[0];
}
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
break;
case DS.TYPE_XML:
if(xhr && oRawResponse.responseXML) {
oFullResponse = oRawResponse.responseXML;
}
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
break;
case DS.TYPE_TEXT:
if(xhr && lang.isString(oRawResponse.responseText)) {
oFullResponse = oRawResponse.responseText;
}
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseTextData(oRequest, oFullResponse);
break;
default:
oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
oParsedResponse = this.parseData(oRequest, oFullResponse);
break;
}
// Clean up for consistent signature
oParsedResponse = oParsedResponse || {};
if(!oParsedResponse.results) {
oParsedResponse.results = [];
}
if(!oParsedResponse.meta) {
oParsedResponse.meta = {};
}
// Success
if(!oParsedResponse.error) {
// Last chance to touch the raw response or the parsed response
oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
this.fireEvent("responseParseEvent", {request:oRequest,
response:oParsedResponse, callback:oCallback, caller:oCaller});
// Cache the response
this.addToCache(oRequest, oParsedResponse);
}
// Error
else {
// Be sure the error flag is on
oParsedResponse.error = true;
this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback,
caller:oCaller, message:DS.ERROR_DATANULL});
YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
}
// Send the response back to the caller
oParsedResponse.tId = tId;
DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
},
/**
* 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.
*
* @method doBeforeParseData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full response from the live database.
* @param oCallback {Object} The callback object.
* @return {Object} Full response for parsing.
*/
doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
return oFullResponse;
},
/**
* 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.
*
* @method doBeforeCallback
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full response from the live database.
* @param oParsedResponse {Object} The parsed response to return to calling object.
* @param oCallback {Object} The callback object.
* @return {Object} Parsed response object.
*/
doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
return oParsedResponse;
},
/**
* Overridable method parses data of generic RESPONSE_TYPE into a response object.
*
* @method parseData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full Array from the live database.
* @return {Object} Parsed response object with the following properties:<br>
* - results {Array} Array of parsed data results<br>
* - meta {Object} Object literal of meta values<br>
* - error {Boolean} (optional) True if there was an error<br>
*/
parseData : function(oRequest, oFullResponse) {
if(lang.isValue(oFullResponse)) {
var oParsedResponse = {results:oFullResponse,meta:{}};
YAHOO.log("Parsed generic data is " +
lang.dump(oParsedResponse), "info", this.toString());
return oParsedResponse;
}
YAHOO.log("Generic data could not be parsed: " + lang.dump(oFullResponse),
"error", this.toString());
return null;
},
/**
* Overridable method parses Array data into a response object.
*
* @method parseArrayData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full Array from the live database.
* @return {Object} Parsed response object with the following properties:<br>
* - results (Array) Array of parsed data results<br>
* - error (Boolean) True if there was an error
*/
parseArrayData : function(oRequest, oFullResponse) {
if(lang.isArray(oFullResponse)) {
var results = [],
i, j,
rec, field, data;
// Parse for fields
if(lang.isArray(this.responseSchema.fields)) {
var fields = this.responseSchema.fields;
for (i = fields.length - 1; i >= 0; --i) {
if (typeof fields[i] !== 'object') {
fields[i] = { key : fields[i] };
}
}
var parsers = {}, p;
for (i = fields.length - 1; i >= 0; --i) {
p = (typeof fields[i].parser === 'function' ?
fields[i].parser :
DS.Parser[fields[i].parser+'']) || fields[i].converter;
if (p) {
parsers[fields[i].key] = p;
}
}
var arrType = lang.isArray(oFullResponse[0]);
for(i=oFullResponse.length-1; i>-1; i--) {
var oResult = {};
rec = oFullResponse[i];
if (typeof rec === 'object') {
for(j=fields.length-1; j>-1; j--) {
field = fields[j];
data = arrType ? rec[j] : rec[field.key];
if (parsers[field.key]) {
data = parsers[field.key].call(this,data);
}
// Safety measure
if(data === undefined) {
data = null;
}
oResult[field.key] = data;
}
}
else if (lang.isString(rec)) {
for(j=fields.length-1; j>-1; j--) {
field = fields[j];
data = rec;
if (parsers[field.key]) {
data = parsers[field.key].call(this,data);
}
// Safety measure
if(data === undefined) {
data = null;
}
oResult[field.key] = data;
}
}
results[i] = oResult;
}
}
// Return entire data set
else {
results = oFullResponse;
}
var oParsedResponse = {results:results};
YAHOO.log("Parsed array data is " +
lang.dump(oParsedResponse), "info", this.toString());
return oParsedResponse;
}
YAHOO.log("Array data could not be parsed: " + lang.dump(oFullResponse),
"error", this.toString());
return null;
},
/**
* Overridable method parses plain text data into a response object.
*
* @method parseTextData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full text response from the live database.
* @return {Object} Parsed response object with the following properties:<br>
* - results (Array) Array of parsed data results<br>
* - error (Boolean) True if there was an error
*/
parseTextData : function(oRequest, oFullResponse) {
if(lang.isString(oFullResponse)) {
if(lang.isString(this.responseSchema.recordDelim) &&
lang.isString(this.responseSchema.fieldDelim)) {
var oParsedResponse = {results:[]};
var recDelim = this.responseSchema.recordDelim;
var fieldDelim = this.responseSchema.fieldDelim;
if(oFullResponse.length > 0) {
// Delete the last line delimiter at the end of the data if it exists
var newLength = oFullResponse.length-recDelim.length;
if(oFullResponse.substr(newLength) == recDelim) {
oFullResponse = oFullResponse.substr(0, newLength);
}
if(oFullResponse.length > 0) {
// Split along record delimiter to get an array of strings
var recordsarray = oFullResponse.split(recDelim);
// Cycle through each record
for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
var bError = false,
sRecord = recordsarray[i];
if (lang.isString(sRecord) && (sRecord.length > 0)) {
// Split each record along field delimiter to get data
var fielddataarray = recordsarray[i].split(fieldDelim);
var oResult = {};
// Filter for fields data
if(lang.isArray(this.responseSchema.fields)) {
var fields = this.responseSchema.fields;
for(var j=fields.length-1; j>-1; j--) {
try {
// Remove quotation marks from edges, if applicable
var data = fielddataarray[j];
if (lang.isString(data)) {
if(data.charAt(0) == "\"") {
data = data.substr(1);
}
if(data.charAt(data.length-1) == "\"") {
data = data.substr(0,data.length-1);
}
var field = fields[j];
var key = (lang.isValue(field.key)) ? field.key : field;
// Backward compatibility
if(!field.parser && field.converter) {
field.parser = field.converter;
YAHOO.log("The field property converter has been deprecated" +
" in favor of parser", "warn", this.toString());
}
var parser = (typeof field.parser === 'function') ?
field.parser :
DS.Parser[field.parser+''];
if(parser) {
data = parser.call(this, data);
}
// Safety measure
if(data === undefined) {
data = null;
}
oResult[key] = data;
}
else {
bError = true;
}
}
catch(e) {
bError = true;
}
}
}
// No fields defined so pass along all data as an array
else {
oResult = fielddataarray;
}
if(!bError) {
oParsedResponse.results[recIdx++] = oResult;
}
}
}
}
}
YAHOO.log("Parsed text data is " +
lang.dump(oParsedResponse), "info", this.toString());
return oParsedResponse;
}
}
YAHOO.log("Text data could not be parsed: " + lang.dump(oFullResponse),
"error", this.toString());
return null;
},
/**
* Overridable method parses XML data for one result into an object literal.
*
* @method parseXMLResult
* @param result {XML} XML for one result.
* @return {Object} Object literal of data for one result.
*/
parseXMLResult : function(result) {
var oResult = {},
schema = this.responseSchema;
try {
// Loop through each data field in each result using the schema
for(var m = schema.fields.length-1; m >= 0 ; m--) {
var field = schema.fields[m];
var key = (lang.isValue(field.key)) ? field.key : field;
var data = null;
if(this.useXPath) {
data = YAHOO.util.DataSource._getLocationValue(field, result);
}
else {
// Values may be held in an attribute...
var xmlAttr = result.attributes.getNamedItem(key);
if(xmlAttr) {
data = xmlAttr.value;
}
// ...or in a node
else {
var xmlNode = result.getElementsByTagName(key);
if(xmlNode && xmlNode.item(0)) {
var item = xmlNode.item(0);
// For IE, then DOM...
data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
// ...then fallback, but check for multiple child nodes
if(!data) {
var datapieces = [];
for(var j=0, len=item.childNodes.length; j<len; j++) {
if(item.childNodes[j].nodeValue) {
datapieces[datapieces.length] = item.childNodes[j].nodeValue;
}
}
if(datapieces.length > 0) {
data = datapieces.join("");
}
}
}
}
}
// Safety net
if(data === null) {
data = "";
}
// Backward compatibility
if(!field.parser && field.converter) {
field.parser = field.converter;
YAHOO.log("The field property converter has been deprecated" +
" in favor of parser", "warn", this.toString());
}
var parser = (typeof field.parser === 'function') ?
field.parser :
DS.Parser[field.parser+''];
if(parser) {
data = parser.call(this, data);
}
// Safety measure
if(data === undefined) {
data = null;
}
oResult[key] = data;
}
}
catch(e) {
YAHOO.log("Error while parsing XML result: " + e.message);
}
return oResult;
},
/**
* Overridable method parses XML data into a response object.
*
* @method parseXMLData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full XML response from the live database.
* @return {Object} Parsed response object with the following properties<br>
* - results (Array) Array of parsed data results<br>
* - error (Boolean) True if there was an error
*/
parseXMLData : function(oRequest, oFullResponse) {
var bError = false,
schema = this.responseSchema,
oParsedResponse = {meta:{}},
xmlList = null,
metaNode = schema.metaNode,
metaLocators = schema.metaFields || {},
i,k,loc,v;
// In case oFullResponse is something funky
try {
// Pull any meta identified
if(this.useXPath) {
for (k in metaLocators) {
oParsedResponse.meta[k] = YAHOO.util.DataSource._getLocationValue(metaLocators[k], oFullResponse);
}
}
else {
metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
oFullResponse;
if (metaNode) {
for (k in metaLocators) {
if (lang.hasOwnProperty(metaLocators, k)) {
loc = metaLocators[k];
// Look for a node
v = metaNode.getElementsByTagName(loc)[0];
if (v) {
v = v.firstChild.nodeValue;
} else {
// Look for an attribute
v = metaNode.attributes.getNamedItem(loc);
if (v) {
v = v.value;
}
}
if (lang.isValue(v)) {
oParsedResponse.meta[k] = v;
}
}
}
}
}
// For result data
xmlList = (schema.resultNode) ?
oFullResponse.getElementsByTagName(schema.resultNode) :
null;
}
catch(e) {
YAHOO.log("Error while parsing XML data: " + e.message);
}
if(!xmlList || !lang.isArray(schema.fields)) {
bError = true;
}
// Loop through each result
else {
oParsedResponse.results = [];
for(i = xmlList.length-1; i >= 0 ; --i) {
var oResult = this.parseXMLResult(xmlList.item(i));
// Capture each array of values into an array of results
oParsedResponse.results[i] = oResult;
}
}
if(bError) {
YAHOO.log("XML data could not be parsed: " +
lang.dump(oFullResponse), "error", this.toString());
oParsedResponse.error = true;
}
else {
YAHOO.log("Parsed XML data is " +
lang.dump(oParsedResponse), "info", this.toString());
}
return oParsedResponse;
},
/**
* Overridable method parses JSON data into a response object.
*
* @method parseJSONData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full JSON from the live database.
* @return {Object} Parsed response object with the following properties<br>
* - results (Array) Array of parsed data results<br>
* - error (Boolean) True if there was an error
*/
parseJSONData : function(oRequest, oFullResponse) {
var oParsedResponse = {results:[],meta:{}};
if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
var schema = this.responseSchema,
fields = schema.fields,
resultsList = oFullResponse,
results = [],
metaFields = schema.metaFields || {},
fieldParsers = [],
fieldPaths = [],
simpleFields = [],
bError = false,
i,len,j,v,key,parser,path;
// Function to convert the schema's fields into walk paths
var buildPath = function (needle) {
var path = null, keys = [], i = 0;
if (needle) {
// Strip the ["string keys"] and [1] array indexes
needle = needle.
replace(/\[(['"])(.*?)\1\]/g,
function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
replace(/\[(\d+)\]/g,
function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
replace(/^\./,''); // remove leading dot
// If the cleaned needle contains invalid characters, the
// path is invalid
if (!/[^\w\.\$@]/.test(needle)) {
path = needle.split('.');
for (i=path.length-1; i >= 0; --i) {
if (path[i].charAt(0) === '@') {
path[i] = keys[parseInt(path[i].substr(1),10)];
}
}
}
else {
YAHOO.log("Invalid locator: " + needle, "error", this.toString());
}
}
return path;
};
// Function to walk a path and return the pot of gold
var walkPath = function (path, origin) {
var v=origin,i=0,len=path.length;
for (;i<len && v;++i) {
v = v[path[i]];
}
return v;
};
// Parse the response
// Step 1. Pull the resultsList from oFullResponse (default assumes
// oFullResponse IS the resultsList)
path = buildPath(schema.resultsList);
if (path) {
resultsList = walkPath(path, oFullResponse);
if (resultsList === undefined) {
bError = true;
}
} else {
bError = true;
}
if (!resultsList) {
resultsList = [];
}
if (!lang.isArray(resultsList)) {
resultsList = [resultsList];
}
if (!bError) {
// Step 2. Parse out field data if identified
if(schema.fields) {
var field;
// Build the field parser map and location paths
for (i=0, len=fields.length; i<len; i++) {
field = fields[i];
key = field.key || field;
parser = ((typeof field.parser === 'function') ?
field.parser :
DS.Parser[field.parser+'']) || field.converter;
path = buildPath(key);
if (parser) {
fieldParsers[fieldParsers.length] = {key:key,parser:parser};
}
if (path) {
if (path.length > 1) {
fieldPaths[fieldPaths.length] = {key:key,path:path};
} else {
simpleFields[simpleFields.length] = {key:key,path:path[0]};
}
} else {
YAHOO.log("Invalid key syntax: " + key,"warn",this.toString());
}
}
// Process the results, flattening the records and/or applying parsers if needed
for (i = resultsList.length - 1; i >= 0; --i) {
var r = resultsList[i], rec = {};
if(r) {
for (j = simpleFields.length - 1; j >= 0; --j) {
// Bug 1777850: data might be held in an array
rec[simpleFields[j].key] =
(r[simpleFields[j].path] !== undefined) ?
r[simpleFields[j].path] : r[j];
}
for (j = fieldPaths.length - 1; j >= 0; --j) {
rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
}
for (j = fieldParsers.length - 1; j >= 0; --j) {
var p = fieldParsers[j].key;
rec[p] = fieldParsers[j].parser.call(this, rec[p]);
if (rec[p] === undefined) {
rec[p] = null;
}
}
}
results[i] = rec;
}
}
else {
results = resultsList;
}
for (key in metaFields) {
if (lang.hasOwnProperty(metaFields,key)) {
path = buildPath(metaFields[key]);
if (path) {
v = walkPath(path, oFullResponse);
oParsedResponse.meta[key] = v;
}
}
}
} else {
YAHOO.log("JSON data could not be parsed due to invalid responseSchema.resultsList or invalid response: " +
lang.dump(oFullResponse), "error", this.toString());
oParsedResponse.error = true;
}
oParsedResponse.results = results;
}
else {
YAHOO.log("JSON data could not be parsed: " +
lang.dump(oFullResponse), "error", this.toString());
oParsedResponse.error = true;
}
return oParsedResponse;
},
/**
* Overridable method parses an HTML TABLE element reference into a response object.
* Data is parsed out of TR elements from all TBODY elements.
*
* @method parseHTMLTableData
* @param oRequest {Object} Request object.
* @param oFullResponse {Object} The full HTML element reference from the live database.
* @return {Object} Parsed response object with the following properties<br>
* - results (Array) Array of parsed data results<br>
* - error (Boolean) True if there was an error
*/
parseHTMLTableData : function(oRequest, oFullResponse) {
var bError = false;
var elTable = oFullResponse;
var fields = this.responseSchema.fields;
var oParsedResponse = {results:[]};
if(lang.isArray(fields)) {
// Iterate through each TBODY
for(var i=0; i<elTable.tBodies.length; i++) {
var elTbody = elTable.tBodies[i];
// Iterate through each TR
for(var j=elTbody.rows.length-1; j>-1; j--) {
var elRow = elTbody.rows[j];
var oResult = {};
for(var k=fields.length-1; k>-1; k--) {
var field = fields[k];
var key = (lang.isValue(field.key)) ? field.key : field;
var data = elRow.cells[k].innerHTML;
// Backward compatibility
if(!field.parser && field.converter) {
field.parser = field.converter;
YAHOO.log("The field property converter has been deprecated" +
" in favor of parser", "warn", this.toString());
}
var parser = (typeof field.parser === 'function') ?
field.parser :
DS.Parser[field.parser+''];
if(parser) {
data = parser.call(this, data);
}
// Safety measure
if(data === undefined) {
data = null;
}
oResult[key] = data;
}
oParsedResponse.results[j] = oResult;
}
}
}
else {
bError = true;
YAHOO.log("Invalid responseSchema.fields", "error", this.toString());
}
if(bError) {
YAHOO.log("HTML TABLE data could not be parsed: " +
lang.dump(oFullResponse), "error", this.toString());
oParsedResponse.error = true;
}
else {
YAHOO.log("Parsed HTML TABLE data is " +
lang.dump(oParsedResponse), "info", this.toString());
}
return oParsedResponse;
}
};
// DataSourceBase uses EventProvider
lang.augmentProto(DS, util.EventProvider);
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* LocalDataSource class for in-memory data structs including JavaScript arrays,
* JavaScript object literals (JSON), XML documents, and HTML tables.
*
* @namespace YAHOO.util
* @class YAHOO.util.LocalDataSource
* @extends YAHOO.util.DataSourceBase
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.LocalDataSource = function(oLiveData, oConfigs) {
this.dataType = DS.TYPE_LOCAL;
if(oLiveData) {
if(YAHOO.lang.isArray(oLiveData)) { // array
this.responseType = DS.TYPE_JSARRAY;
}
// xml
else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
this.responseType = DS.TYPE_XML;
}
else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
this.responseType = DS.TYPE_HTMLTABLE;
oLiveData = oLiveData.cloneNode(true);
}
else if(YAHOO.lang.isString(oLiveData)) { // text
this.responseType = DS.TYPE_TEXT;
}
else if(YAHOO.lang.isObject(oLiveData)) { // json
this.responseType = DS.TYPE_JSON;
}
}
else {
oLiveData = [];
this.responseType = DS.TYPE_JSARRAY;
}
util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
};
// LocalDataSource extends DataSourceBase
lang.extend(util.LocalDataSource, DS);
// Copy static members to LocalDataSource class
lang.augmentObject(util.LocalDataSource, DS);
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* FunctionDataSource class for JavaScript functions.
*
* @namespace YAHOO.util
* @class YAHOO.util.FunctionDataSource
* @extends YAHOO.util.DataSourceBase
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.FunctionDataSource = function(oLiveData, oConfigs) {
this.dataType = DS.TYPE_JSFUNCTION;
oLiveData = oLiveData || function() {};
util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
};
// FunctionDataSource extends DataSourceBase
lang.extend(util.FunctionDataSource, DS, {
/////////////////////////////////////////////////////////////////////////////
//
// FunctionDataSource public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Context in which to execute the function. By default, is the DataSource
* instance itself. If set, the function will receive the DataSource instance
* as an additional argument.
*
* @property scope
* @type Object
* @default null
*/
scope : null,
/////////////////////////////////////////////////////////////////////////////
//
// FunctionDataSource public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Overriding method passes query to a function. The returned response is then
* forwarded to the handleResponse function.
*
* @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});
// Pass the request in as a parameter and
// forward the return value to the handler
var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this, oCallback) : this.liveData(oRequest, oCallback);
// Try to sniff data type if it has not been defined
if(this.responseType === DS.TYPE_UNKNOWN) {
if(YAHOO.lang.isArray(oRawResponse)) { // array
this.responseType = DS.TYPE_JSARRAY;
}
// xml
else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
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;
}
}
this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
return tId;
}
});
// Copy static members to FunctionDataSource class
lang.augmentObject(util.FunctionDataSource, DS);
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* ScriptNodeDataSource class for accessing remote data via the YUI Get Utility.
*
* @namespace YAHOO.util
* @class YAHOO.util.ScriptNodeDataSource
* @extends YAHOO.util.DataSourceBase
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
this.dataType = DS.TYPE_SCRIPTNODE;
oLiveData = oLiveData || "";
util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
};
// ScriptNodeDataSource extends DataSourceBase
lang.extend(util.ScriptNodeDataSource, DS, {
/////////////////////////////////////////////////////////////////////////////
//
// ScriptNodeDataSource public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Alias to YUI Get Utility, to allow implementers to use a custom class.
*
* @property getUtility
* @type Object
* @default YAHOO.util.Get
*/
getUtility : util.Get,
/**
* Defines request/response management in the following manner:
* <dl>
* <!--<dt>queueRequests</dt>
* <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
* <dt>cancelStaleRequests</dt>
* <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
* <dt>ignoreStaleResponses</dt>
* <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
* <dt>allowAll</dt>
* <dd>Send all requests and handle all responses.</dd>
* </dl>
*
* @property asyncMode
* @type String
* @default "allowAll"
*/
asyncMode : "allowAll",
/**
* Callback string parameter name sent to the remote script. By default,
* requests are sent to
* <URI>?<scriptCallbackParam>=callback
*
* @property scriptCallbackParam
* @type String
* @default "callback"
*/
scriptCallbackParam : "callback",
/////////////////////////////////////////////////////////////////////////////
//
// ScriptNodeDataSource public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Creates a request callback that gets appended to the script URI. Implementers
* can customize this string to match their server's query syntax.
*
* @method generateRequestCallback
* @return {String} String fragment that gets appended to script URI that
* specifies the callback function
*/
generateRequestCallback : function(id) {
return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
},
/**
* Overridable method gives implementers access to modify the URI before the dynamic
* script node gets inserted. Implementers should take care not to return an
* invalid URI.
*
* @method doBeforeGetScriptNode
* @param {String} URI to the script
* @return {String} URI to the script
*/
doBeforeGetScriptNode : function(sUri) {
return sUri;
},
/**
* Overriding method passes query to Get Utility. The returned
* response is then forwarded to the handleResponse function.
*
* @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});
// If there are no global pending requests, it is safe to purge global callback stack and global counter
if(util.ScriptNodeDataSource._nPending === 0) {
util.ScriptNodeDataSource.callbacks = [];
util.ScriptNodeDataSource._nId = 0;
}
// ID for this request
var id = util.ScriptNodeDataSource._nId;
util.ScriptNodeDataSource._nId++;
// Dynamically add handler function with a closure to the callback stack
var oSelf = this;
util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) {
if((oSelf.asyncMode !== "ignoreStaleResponses")||
(id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses
// Try to sniff data type if it has not been defined
if(oSelf.responseType === DS.TYPE_UNKNOWN) {
if(YAHOO.lang.isArray(oRawResponse)) { // array
oSelf.responseType = DS.TYPE_JSARRAY;
}
// xml
else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) {
oSelf.responseType = DS.TYPE_XML;
}
else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
oSelf.responseType = DS.TYPE_HTMLTABLE;
}
else if(YAHOO.lang.isObject(oRawResponse)) { // json
oSelf.responseType = DS.TYPE_JSON;
}
else if(YAHOO.lang.isString(oRawResponse)) { // text
oSelf.responseType = DS.TYPE_TEXT;
}
}
oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
}
else {
YAHOO.log("DataSource ignored stale response for tId " + tId + "(" + oRequest + ")", "info", oSelf.toString());
}
delete util.ScriptNodeDataSource.callbacks[id];
};
// We are now creating a request
util.ScriptNodeDataSource._nPending++;
var sUri = this.liveData + oRequest + this.generateRequestCallback(id);
sUri = this.doBeforeGetScriptNode(sUri);
YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString());
this.getUtility.script(sUri,
{autopurge: true,
onsuccess: util.ScriptNodeDataSource._bumpPendingDown,
onfail: util.ScriptNodeDataSource._bumpPendingDown});
return tId;
}
});
// Copy static members to ScriptNodeDataSource class
lang.augmentObject(util.ScriptNodeDataSource, DS);
// Copy static members to ScriptNodeDataSource class
lang.augmentObject(util.ScriptNodeDataSource, {
/////////////////////////////////////////////////////////////////////////////
//
// ScriptNodeDataSource private static properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Unique ID to track requests.
*
* @property _nId
* @type Number
* @private
* @static
*/
_nId : 0,
/**
* Counter for pending requests. When this is 0, it is safe to purge callbacks
* array.
*
* @property _nPending
* @type Number
* @private
* @static
*/
_nPending : 0,
/**
* Global array of callback functions, one for each request sent.
*
* @property callbacks
* @type Function[]
* @static
*/
callbacks : []
});
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* XHRDataSource class for accessing remote data via the YUI Connection Manager
* Utility
*
* @namespace YAHOO.util
* @class YAHOO.util.XHRDataSource
* @extends YAHOO.util.DataSourceBase
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.XHRDataSource = function(oLiveData, oConfigs) {
this.dataType = DS.TYPE_XHR;
this.connMgr = this.connMgr || util.Connect;
oLiveData = oLiveData || "";
util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
};
// XHRDataSource extends DataSourceBase
lang.extend(util.XHRDataSource, DS, {
/////////////////////////////////////////////////////////////////////////////
//
// XHRDataSource public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Alias to YUI Connection Manager, to allow implementers to use a custom class.
*
* @property connMgr
* @type Object
* @default YAHOO.util.Connect
*/
connMgr: null,
/**
* Defines request/response management in the following manner:
* <dl>
* <dt>queueRequests</dt>
* <dd>If a request is already in progress, wait until response is returned
* before sending the next request.</dd>
*
* <dt>cancelStaleRequests</dt>
* <dd>If a request is already in progress, cancel it before sending the next
* request.</dd>
*
* <dt>ignoreStaleResponses</dt>
* <dd>Send all requests, but handle only the response for the most recently
* sent request.</dd>
*
* <dt>allowAll</dt>
* <dd>Send all requests and handle all responses.</dd>
*
* </dl>
*
* @property connXhrMode
* @type String
* @default "allowAll"
*/
connXhrMode: "allowAll",
/**
* True if data is to be sent via POST. By default, data will be sent via GET.
*
* @property connMethodPost
* @type Boolean
* @default false
*/
connMethodPost: false,
/**
* The connection timeout defines how many milliseconds the XHR connection will
* wait for a server response. Any non-zero value will enable the Connection Manager's
* Auto-Abort feature.
*
* @property connTimeout
* @type Number
* @default 0
*/
connTimeout: 0,
/////////////////////////////////////////////////////////////////////////////
//
// XHRDataSource public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Overriding method passes query to Connection Manager. The returned
* response is then forwarded to the handleResponse function.
*
* @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 oRawResponse = null;
var tId = DS._nTransactionId++;
this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
// Set up the callback object and
// pass the request in as a URL query and
// forward the response to the handler
var oSelf = this;
var oConnMgr = this.connMgr;
var oQueue = this._oQueue;
/**
* Define Connection Manager success handler
*
* @method _xhrSuccess
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrSuccess = function(oResponse) {
// If response ID does not match last made request ID,
// silently fail and wait for the next response
if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
(oResponse.tId != oQueue.conn.tId)) {
YAHOO.log("Ignored stale response", "warn", this.toString());
return null;
}
// Error if no response
else if(!oResponse) {
this.fireEvent("dataErrorEvent", {request:oRequest, response:null,
callback:oCallback, caller:oCaller,
message:DS.ERROR_DATANULL});
YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
// Send error response back to the caller with the error flag on
DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);
return null;
}
// Forward to handler
else {
// Try to sniff data type if it has not been defined
if(this.responseType === DS.TYPE_UNKNOWN) {
var ctype = (oResponse.getResponseHeader) ? oResponse.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;
}
}
}
this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
}
};
/**
* Define Connection Manager failure handler
*
* @method _xhrFailure
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrFailure = function(oResponse) {
this.fireEvent("dataErrorEvent", {request:oRequest, response: oResponse,
callback:oCallback, caller:oCaller,
message:DS.ERROR_DATAINVALID});
YAHOO.log(DS.ERROR_DATAINVALID + ": " +
oResponse.statusText, "error", this.toString());
// Backward compatibility
if(lang.isString(this.liveData) && lang.isString(oRequest) &&
(this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
(oRequest.indexOf("?") !== 0)){
YAHOO.log("DataSources using XHR no longer automatically supply " +
"a \"?\" between the host and query parameters" +
" -- please check that the request URL is correct", "warn", this.toString());
}
// Send failure response back to the caller with the error flag on
oResponse = oResponse || {};
oResponse.error = true;
DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller);
return null;
};
/**
* Define Connection Manager callback object
*
* @property _xhrCallback
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrCallback = {
success:_xhrSuccess,
failure:_xhrFailure,
scope: this
};
// Apply Connection Manager timeout
if(lang.isNumber(this.connTimeout)) {
_xhrCallback.timeout = this.connTimeout;
}
// Cancel stale requests
if(this.connXhrMode == "cancelStaleRequests") {
// Look in queue for stale requests
if(oQueue.conn) {
if(oConnMgr.abort) {
oConnMgr.abort(oQueue.conn);
oQueue.conn = null;
YAHOO.log("Canceled stale request", "warn", this.toString());
}
else {
YAHOO.log("Could not find Connection Manager abort() function", "error", this.toString());
}
}
}
// Get ready to send the request URL
if(oConnMgr && oConnMgr.asyncRequest) {
var sLiveData = this.liveData;
var isPost = this.connMethodPost;
var sMethod = (isPost) ? "POST" : "GET";
// Validate request
var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest;
var sRequest = (isPost) ? oRequest : null;
// Send the request right away
if(this.connXhrMode != "queueRequests") {
oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
}
// Queue up then send the request
else {
// Found a request already in progress
if(oQueue.conn) {
var allRequests = oQueue.requests;
// Add request to queue
allRequests.push({request:oRequest, callback:_xhrCallback});
// Interval needs to be started
if(!oQueue.interval) {
oQueue.interval = setInterval(function() {
// Connection is in progress
if(oConnMgr.isCallInProgress(oQueue.conn)) {
return;
}
else {
// Send next request
if(allRequests.length > 0) {
// Validate request
sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request;
sRequest = (isPost) ? allRequests[0].request : null;
oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest);
// Remove request from queue
allRequests.shift();
}
// No more requests
else {
clearInterval(oQueue.interval);
oQueue.interval = null;
}
}
}, 50);
}
}
// Nothing is in progress
else {
oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
}
}
}
else {
YAHOO.log("Could not find Connection Manager asyncRequest() function", "error", this.toString());
// Send null response back to the caller with the error flag on
DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);
}
return tId;
}
});
// Copy static members to XHRDataSource class
lang.augmentObject(util.XHRDataSource, DS);
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* Factory class for creating a BaseDataSource subclass instance. The sublcass is
* determined by oLiveData's type, unless the dataType config is explicitly passed in.
*
* @namespace YAHOO.util
* @class YAHOO.util.DataSource
* @constructor
* @param oLiveData {HTMLElement} Pointer to live data.
* @param oConfigs {object} (optional) Object literal of configuration values.
*/
util.DataSource = function(oLiveData, oConfigs) {
oConfigs = oConfigs || {};
// Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type.
var dataType = oConfigs.dataType;
if(dataType) {
if(dataType == DS.TYPE_LOCAL) {
return new util.LocalDataSource(oLiveData, oConfigs);
}
else if(dataType == DS.TYPE_XHR) {
return new util.XHRDataSource(oLiveData, oConfigs);
}
else if(dataType == DS.TYPE_SCRIPTNODE) {
return new util.ScriptNodeDataSource(oLiveData, oConfigs);
}
else if(dataType == DS.TYPE_JSFUNCTION) {
return new util.FunctionDataSource(oLiveData, oConfigs);
}
}
if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr
return new util.XHRDataSource(oLiveData, oConfigs);
}
else if(YAHOO.lang.isFunction(oLiveData)) {
return new util.FunctionDataSource(oLiveData, oConfigs);
}
else { // ultimate default is local
return new util.LocalDataSource(oLiveData, oConfigs);
}
};
// Copy static members to DataSource class
lang.augmentObject(util.DataSource, DS);
})();
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The static Number class provides helper functions to deal with data of type
* Number.
*
* @namespace YAHOO.util
* @requires yahoo
* @class Number
* @static
*/
YAHOO.util.Number = {
/**
* Takes a native JavaScript Number and formats to a string for display.
*
* @method format
* @param nData {Number} Number.
* @param oConfig {Object} (Optional) Optional configuration values:
* <dl>
* <dt>format</dt>
* <dd>String used as a template for formatting positive numbers.
* {placeholders} in the string are applied from the values in this
* config object. {number} is used to indicate where the numeric portion
* of the output goes. For example "{prefix}{number} per item"
* might yield "$5.25 per item". The only required
* {placeholder} is {number}.</dd>
*
* <dt>negativeFormat</dt>
* <dd>Like format, but applied to negative numbers. If set to null,
* defaults from the configured format, prefixed with -. This is
* separate from format to support formats like "($12,345.67)".
*
* <dt>prefix {String} (deprecated, use format/negativeFormat)</dt>
* <dd>String prepended before each number, like a currency designator "$"</dd>
* <dt>decimalPlaces {Number}</dt>
* <dd>Number of decimal places to round.</dd>
*
* <dt>decimalSeparator {String}</dt>
* <dd>Decimal separator</dd>
*
* <dt>thousandsSeparator {String}</dt>
* <dd>Thousands separator</dd>
*
* <dt>suffix {String} (deprecated, use format/negativeFormat)</dt>
* <dd>String appended after each number, like " items" (note the space)</dd>
* </dl>
* @return {String} Formatted number for display. Note, the following values
* return as "": null, undefined, NaN, "".
*/
format : function(n, cfg) {
if (n === '' || n === null || !isFinite(n)) {
return '';
}
n = +n;
cfg = YAHOO.lang.merge(YAHOO.util.Number.format.defaults, (cfg || {}));
var stringN = n+'',
absN = Math.abs(n),
places = cfg.decimalPlaces || 0,
sep = cfg.thousandsSeparator,
negFmt = cfg.negativeFormat || ('-' + cfg.format),
s, bits, i, precision;
if (negFmt.indexOf('#') > -1) {
// for backward compatibility of negativeFormat supporting '-#'
negFmt = negFmt.replace(/#/, cfg.format);
}
if (places < 0) {
// Get rid of the decimal info
s = absN - (absN % 1) + '';
i = s.length + places;
// avoid 123 vs decimalPlaces -4 (should return "0")
if (i > 0) {
// leverage toFixed by making 123 => 0.123 for the rounding
// operation, then add the appropriate number of zeros back on
s = Number('.' + s).toFixed(i).slice(2) +
new Array(s.length - i + 1).join('0');
} else {
s = "0";
}
} else {
// Avoid toFixed on floats:
// Bug 2528976
// Bug 2528977
var unfloatedN = absN+'';
if(places > 0 || unfloatedN.indexOf('.') > 0) {
var power = Math.pow(10, places);
s = Math.round(absN * power) / power + '';
var dot = s.indexOf('.'),
padding, zeroes;
// Add padding
if(dot < 0) {
padding = places;
zeroes = (Math.pow(10, padding) + '').substring(1);
if(places > 0) {
s = s + '.' + zeroes;
}
}
else {
padding = places - (s.length - dot - 1);
zeroes = (Math.pow(10, padding) + '').substring(1);
s = s + zeroes;
}
}
else {
s = absN.toFixed(places)+'';
}
}
bits = s.split(/\D/);
if (absN >= 1000) {
i = bits[0].length % 3 || 3;
bits[0] = bits[0].slice(0,i) +
bits[0].slice(i).replace(/(\d{3})/g, sep + '$1');
}
return YAHOO.util.Number.format._applyFormat(
(n < 0 ? negFmt : cfg.format),
bits.join(cfg.decimalSeparator),
cfg);
}
};
/**
* <p>Default values for Number.format behavior. Override properties of this
* object if you want every call to Number.format in your system to use
* specific presets.</p>
*
* <p>Available keys include:</p>
* <ul>
* <li>format</li>
* <li>negativeFormat</li>
* <li>decimalSeparator</li>
* <li>decimalPlaces</li>
* <li>thousandsSeparator</li>
* <li>prefix/suffix or any other token you want to use in the format templates</li>
* </ul>
*
* @property Number.format.defaults
* @type {Object}
* @static
*/
YAHOO.util.Number.format.defaults = {
format : '{prefix}{number}{suffix}',
negativeFormat : null, // defaults to -(format)
decimalSeparator : '.',
decimalPlaces : null,
thousandsSeparator : ''
};
/**
* Apply any special formatting to the "d,ddd.dd" string. Takes either the
* cfg.format or cfg.negativeFormat template and replaces any {placeholders}
* with either the number or a value from a so-named property of the config
* object.
*
* @method Number.format._applyFormat
* @static
* @param tmpl {String} the cfg.format or cfg.numberFormat template string
* @param num {String} the number with separators and decimalPlaces applied
* @param data {Object} the config object, used here to populate {placeholder}s
* @return {String} the number with any decorators added
*/
YAHOO.util.Number.format._applyFormat = function (tmpl, num, data) {
return tmpl.replace(/\{(\w+)\}/g, function (_, token) {
return token === 'number' ? num :
token in data ? data[token] : '';
});
};
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
(function () {
var xPad=function (x, pad, r)
{
if(typeof r === 'undefined')
{
r=10;
}
for( ; parseInt(x, 10)<r && r>1; r/=10) {
x = pad.toString() + x;
}
return x.toString();
};
/**
* The static Date class provides helper functions to deal with data of type Date.
*
* @namespace YAHOO.util
* @requires yahoo
* @class Date
* @static
*/
var Dt = {
formats: {
a: function (d, l) { return l.a[d.getDay()]; },
A: function (d, l) { return l.A[d.getDay()]; },
b: function (d, l) { return l.b[d.getMonth()]; },
B: function (d, l) { return l.B[d.getMonth()]; },
C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); },
d: ['getDate', '0'],
e: ['getDate', ' '],
g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); },
G: function (d) {
var y = d.getFullYear();
var V = parseInt(Dt.formats.V(d), 10);
var W = parseInt(Dt.formats.W(d), 10);
if(W > V) {
y++;
} else if(W===0 && V>=52) {
y--;
}
return y;
},
H: ['getHours', '0'],
I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); },
j: function (d) {
var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT');
var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT');
var ms = gmdate - gmd_1;
var doy = parseInt(ms/60000/60/24, 10)+1;
return xPad(doy, 0, 100);
},
k: ['getHours', ' '],
l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); },
m: function (d) { return xPad(d.getMonth()+1, 0); },
M: ['getMinutes', '0'],
p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; },
P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; },
s: function (d, l) { return parseInt(d.getTime()/1000, 10); },
S: ['getSeconds', '0'],
u: function (d) { var dow = d.getDay(); return dow===0?7:dow; },
U: function (d) {
var doy = parseInt(Dt.formats.j(d), 10);
var rdow = 6-d.getDay();
var woy = parseInt((doy+rdow)/7, 10);
return xPad(woy, 0);
},
V: function (d) {
var woy = parseInt(Dt.formats.W(d), 10);
var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
// First week is 01 and not 00 as in the case of %U and %W,
// so we add 1 to the final result except if day 1 of the year
// is a Monday (then %W returns 01).
// We also need to subtract 1 if the day 1 of the year is
// Friday-Sunday, so the resulting equation becomes:
var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
{
idow = 1;
}
else if(idow === 0)
{
idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
}
return xPad(idow, 0);
},
w: 'getDay',
W: function (d) {
var doy = parseInt(Dt.formats.j(d), 10);
var rdow = 7-Dt.formats.u(d);
var woy = parseInt((doy+rdow)/7, 10);
return xPad(woy, 0, 10);
},
y: function (d) { return xPad(d.getFullYear()%100, 0); },
Y: 'getFullYear',
z: function (d) {
var o = d.getTimezoneOffset();
var H = xPad(parseInt(Math.abs(o/60), 10), 0);
var M = xPad(Math.abs(o%60), 0);
return (o>0?'-':'+') + H + M;
},
Z: function (d) {
var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, '');
if(tz.length > 4) {
tz = Dt.formats.z(d);
}
return tz;
},
'%': function (d) { return '%'; }
},
aggregates: {
c: 'locale',
D: '%m/%d/%y',
F: '%Y-%m-%d',
h: '%b',
n: '\n',
r: 'locale',
R: '%H:%M',
t: '\t',
T: '%H:%M:%S',
x: 'locale',
X: 'locale'
//'+': '%a %b %e %T %Z %Y'
},
/**
* Takes a native JavaScript Date and formats to string for display to user.
*
* @method format
* @param oDate {Date} Date.
* @param oConfig {Object} (Optional) Object literal of configuration values:
* <dl>
* <dt>format <String></dt>
* <dd>
* <p>
* Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at
* <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a>
* </p>
* <p>
* PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a>
* </p>
* <p>
* This javascript implementation supports all the PHP specifiers and a few more. The full list is below:
* </p>
* <dl>
* <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd>
* <dt>%A</dt> <dd>full weekday name according to the current locale</dd>
* <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd>
* <dt>%B</dt> <dd>full month name according to the current locale</dd>
* <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd>
* <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd>
* <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd>
* <dt>%D</dt> <dd>same as %m/%d/%y</dd>
* <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>
* <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd>
* <dt>%g</dt> <dd>like %G, but without the century</dd>
* <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd>
* <dt>%h</dt> <dd>same as %b</dd>
* <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd>
* <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd>
* <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd>
* <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>
* <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>
* <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd>
* <dt>%M</dt> <dd>minute as a decimal number</dd>
* <dt>%n</dt> <dd>newline character</dd>
* <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd>
* <dt>%P</dt> <dd>like %p, but lower case</dd>
* <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd>
* <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd>
* <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd>
* <dt>%S</dt> <dd>second as a decimal number</dd>
* <dt>%t</dt> <dd>tab character</dd>
* <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd>
* <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd>
* <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the
* first Sunday as the first day of the first week</dd>
* <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number,
* range 01 to 53, where week 1 is the first week that has at least 4 days
* in the current year, and with Monday as the first day of the week.</dd>
* <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd>
* <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the
* first Monday as the first day of the first week</dd>
* <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd>
* <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd>
* <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd>
* <dt>%Y</dt> <dd>year as a decimal number including the century</dd>
* <dt>%z</dt> <dd>numerical time zone representation</dd>
* <dt>%Z</dt> <dd>time zone name or abbreviation</dd>
* <dt>%%</dt> <dd>a literal `%' character</dd>
* </dl>
* </dd>
* </dl>
* @param sLocale {String} (Optional) The locale to use when displaying days of week,
* months of the year, and other locale specific strings. The following locales are
* built in:
* <dl>
* <dt>en</dt>
* <dd>English</dd>
* <dt>en-US</dt>
* <dd>US English</dd>
* <dt>en-GB</dt>
* <dd>British English</dd>
* <dt>en-AU</dt>
* <dd>Australian English (identical to British English)</dd>
* </dl>
* More locales may be added by subclassing of YAHOO.util.DateLocale.
* See YAHOO.util.DateLocale for more information.
* @return {HTML} Formatted date for display. Non-date values are passed
* through as-is.
* @sa YAHOO.util.DateLocale
*/
format : function (oDate, oConfig, sLocale) {
oConfig = oConfig || {};
if(!(oDate instanceof Date)) {
return YAHOO.lang.isValue(oDate) ? oDate : "";
}
var format = oConfig.format || "%m/%d/%Y";
// Be backwards compatible, support strings that are
// exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY
if(format === 'YYYY/MM/DD') {
format = '%Y/%m/%d';
} else if(format === 'DD/MM/YYYY') {
format = '%d/%m/%Y';
} else if(format === 'MM/DD/YYYY') {
format = '%m/%d/%Y';
}
// end backwards compatibility block
sLocale = sLocale || "en";
// Make sure we have a definition for the requested locale, or default to en.
if(!(sLocale in YAHOO.util.DateLocale)) {
if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) {
sLocale = sLocale.replace(/-[a-zA-Z]+$/, '');
} else {
sLocale = "en";
}
}
var aLocale = YAHOO.util.DateLocale[sLocale];
var replace_aggs = function (m0, m1) {
var f = Dt.aggregates[m1];
return (f === 'locale' ? aLocale[m1] : f);
};
var replace_formats = function (m0, m1) {
var f = Dt.formats[m1];
if(typeof f === 'string') { // string => built in date function
return oDate[f]();
} else if(typeof f === 'function') { // function => our own function
return f.call(oDate, oDate, aLocale);
} else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding
return xPad(oDate[f[0]](), f[1]);
} else {
return m1;
}
};
// First replace aggregates (run in a loop because an agg may be made up of other aggs)
while(format.match(/%[cDFhnrRtTxX]/)) {
format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs);
}
// Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a)
var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats);
replace_aggs = replace_formats = undefined;
return str;
}
};
YAHOO.namespace("YAHOO.util");
YAHOO.util.Date = Dt;
/**
* The DateLocale class is a container and base class for all
* localised date strings used by YAHOO.util.Date. It is used
* internally, but may be extended to provide new date localisations.
*
* To create your own DateLocale, follow these steps:
* <ol>
* <li>Find an existing locale that matches closely with your needs</li>
* <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing
* matches.</li>
* <li>Create your own class as an extension of the base class using
* YAHOO.lang.merge, and add your own localisations where needed.</li>
* </ol>
* See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB']
* classes which extend YAHOO.util.DateLocale['en'].
*
* For example, to implement locales for French french and Canadian french,
* we would do the following:
* <ol>
* <li>For French french, we have no existing similar locale, so use
* YAHOO.util.DateLocale as the base, and extend it:
* <pre>
* YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {
* a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'],
* A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
* b: ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'],
* B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
* c: '%a %d %b %Y %T %Z',
* p: ['', ''],
* P: ['', ''],
* x: '%d.%m.%Y',
* X: '%T'
* });
* </pre>
* </li>
* <li>For Canadian french, we start with French french and change the meaning of \%x:
* <pre>
* YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], {
* x: '%Y-%m-%d'
* });
* </pre>
* </li>
* </ol>
*
* With that, you can use your new locales:
* <pre>
* var d = new Date("2008/04/22");
* YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr");
* </pre>
* will return:
* <pre>
* mardi, 22 avril == 22.04.2008
* </pre>
* And
* <pre>
* YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA");
* </pre>
* Will return:
* <pre>
* mardi, 22 avril == 2008-04-22
* </pre>
* @namespace YAHOO.util
* @requires yahoo
* @class DateLocale
*/
YAHOO.util.DateLocale = {
a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
c: '%a %d %b %Y %T %Z',
p: ['AM', 'PM'],
P: ['am', 'pm'],
r: '%I:%M:%S %p',
x: '%d/%m/%y',
X: '%T'
};
YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {});
YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
c: '%a %d %b %Y %I:%M:%S %p %Z',
x: '%m/%d/%Y',
X: '%I:%M:%S %p'
});
YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
r: '%l:%M:%S %P %Z'
});
YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']);
})();
YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.9.0", build: "2800"});