root/trunk/jsondatasource.js

Revision 117, 1.9 kB (checked in by mischa, 3 years ago)

add option to pass in data to be sent with request

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// this is a datasource abstract base class which will retreive
2// data from a server endpoint with JSON
3
4// takes URL, data updated callback, options
5// options.noFetch == don't automatically retrieve data when initialized
6JSONDataSource = new Class (DataSource, {
7
8  init: function (endPoint, dataUpdatedCallback, opts) {
9    JSONDataSource.superClass.init.apply(this, []);
10    this.endPoint = endPoint;
11    this.dataUpdatedCallback = dataUpdatedCallback;
12    this.currentOperationCallback = null;
13
14    if (opts && opts.method)
15        this.method = opts.method;
16
17    if (opts && opts.data)
18        this.reqData = opts.data;
19
20    if (opts && opts.onError) {
21        this.onError = opts.onError;
22    } else {
23        this.onError = this.defaultErrorHandler;
24    }
25
26    if (!opts || !opts["noFetch"])
27      this.getData();
28
29    this.hourglass = null;
30  },
31
32  update: function (opts) {
33    opts = opts ? opts : {};
34    var hourglassOnWidget = opts["hourglassOnWidget"];
35    var callback = opts["callback"];
36    if (callback)
37      this.currentOperationCallback = callback;
38
39    if (hourglassOnWidget) {
40      this.hourglass = new Hourglass();
41      this.hourglass.init(hourglassOnWidget);
42    }
43    this.getData();
44  },
45
46  receivedData: function (data) {
47    this.theData = data;
48    this.callWatchers();
49
50    if (this.dataUpdatedCallback)
51      this.dataUpdatedCallback(data);
52
53    if (this.hourglass) {
54      this.hourglass.hide();
55      this.hourglass = null;
56    }
57
58    if (this.currentOperationCallback)
59      this.currentOperationCallback(data);
60  },
61
62  getData: function () {
63    var reqOpts = {};
64    reqOpts.onError = this.onError.bind(this);
65    reqOpts.url = this.endPoint;
66    reqOpts.onData = this.receivedData.bind(this);
67
68    if (this.reqData)
69        reqOpts.data = this.reqData;
70
71    if (this.method)
72        reqOpts.method = this.method;
73
74    HTTPReq.getJSON(reqOpts);
75  },
76
77  defaultErrorHandler: function (err) {
78    alert("Error: " + err);
79  }
80});
Note: See TracBrowser for help on using the browser.