3 * A sample AJAX data store implementation.
4 * Right now, it's hooked up to load Hackernews stories, but can
5 * easily be extended to support any JSONP-compatible backend that accepts paging parameters.
7 function RemoteModel() {
10 var data = {length: 0};
15 var req = null; // ajax request
18 var onDataLoading = new Slick.Event();
19 var onDataLoaded = new Slick.Event();
26 function isDataLoaded(from, to) {
27 for (var i = from; i <= to; i++) {
28 if (data[i] == undefined || data[i] == null) {
38 for (var key in data) {
45 function ensureData(from, to) {
48 for (var i = req.fromPage; i <= req.toPage; i++)
49 data[i * PAGESIZE] = undefined;
56 if (data.length > 0) {
57 to = Math.min(to, data.length - 1);
60 var fromPage = Math.floor(from / PAGESIZE);
61 var toPage = Math.floor(to / PAGESIZE);
63 while (data[fromPage * PAGESIZE] !== undefined && fromPage < toPage)
66 while (data[toPage * PAGESIZE] !== undefined && fromPage < toPage)
69 if (fromPage > toPage || ((fromPage == toPage) && data[fromPage * PAGESIZE] !== undefined)) {
71 onDataLoaded.notify({from: from, to: to});
75 var url = "http://api.thriftdb.com/api.hnsearch.com/items/_search?filter[fields][type][]=submission&q=" + searchstr + "&start=" + (fromPage * PAGESIZE) + "&limit=" + (((toPage - fromPage) * PAGESIZE) + PAGESIZE);
77 if (sortcol != null) {
78 url += ("&sortby=" + sortcol + ((sortdir > 0) ? "+asc" : "+desc"));
81 if (h_request != null) {
82 clearTimeout(h_request);
85 h_request = setTimeout(function () {
86 for (var i = fromPage; i <= toPage; i++)
87 data[i * PAGESIZE] = null; // null indicates a 'requested but not available yet'
89 onDataLoading.notify({from: from, to: to});
93 callbackParameter: "callback",
97 onError(fromPage, toPage)
100 req.fromPage = fromPage;
106 function onError(fromPage, toPage) {
107 alert("error loading pages " + fromPage + " to " + toPage);
110 function onSuccess(resp) {
111 var from = resp.request.start, to = from + resp.results.length;
112 data.length = Math.min(parseInt(resp.hits),1000); // limitation of the API
114 for (var i = 0; i < resp.results.length; i++) {
115 var item = resp.results[i].item;
117 // Old IE versions can't parse ISO dates, so change to universally-supported format.
118 item.create_ts = item.create_ts.replace(/^(\d+)-(\d+)-(\d+)T(\d+:\d+:\d+)Z$/, "$2/$3/$1 $4 UTC");
119 item.create_ts = new Date(item.create_ts);
121 data[from + i] = item;
122 data[from + i].index = from + i;
127 onDataLoaded.notify({from: from, to: to});
131 function reloadData(from, to) {
132 for (var i = from; i <= to; i++)
135 ensureData(from, to);
139 function setSort(column, dir) {
145 function setSearch(str) {
159 "isDataLoaded": isDataLoaded,
160 "ensureData": ensureData,
161 "reloadData": reloadData,
163 "setSearch": setSearch,
166 "onDataLoading": onDataLoading,
167 "onDataLoaded": onDataLoaded
171 // Slick.Data.RemoteModel
172 $.extend(true, window, { Slick: { Data: { RemoteModel: RemoteModel }}});