-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel.js
More file actions
72 lines (56 loc) · 1.56 KB
/
model.js
File metadata and controls
72 lines (56 loc) · 1.56 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
"use strict";
const XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;
const HOST = 'https://javascriptru.firebaseio.com';
export default class Model {
constructor(opts, data) {
this._resource = opts.resource;
this._key = opts.key;
this.setData(data)
}
setData(data) {
this.data = data;
}
getData() {
return this.data;
}
setKey(key) {
alert('New key set: ' + key);
this._key = key;
}
fetch(done, fail) {
this._request('GET', null, (xhr) => {
this.setData(JSON.parse(xhr.responseText));
done && done(this, xhr);
}, fail);
}
save(done, fail) {
let method = this._key ? 'PUT' : 'POST';
this._request(method, this.data, (xhr) => {
if (method === 'POST') {
this.setKey(JSON.parse(xhr.responseText).name);
} else if (method === 'PUT') {
this.setData(JSON.parse(xhr.responseText));
}
done && done(this, xhr, method);
}, fail);
}
_getUrl() {
let url = `${HOST}/${this._resource}`;
if (this._key) {
url += `/${this._key}`;
}
return `${url}.json`;
}
_request(method, data, callback, errback) {
let xhr = new XHR(),
model = this;
xhr.open(method, this._getUrl(), true);
xhr.onload = function (event) {
callback.call(this, this, event, model);
};
xhr.onerror = function (event) {
//TODO: Do smth on errors
};
xhr.send(JSON.stringify(data || {}));
}
}