forked from webduinoio/webduino-blockly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONStorage.js
More file actions
89 lines (75 loc) · 2.33 KB
/
JSONStorage.js
File metadata and controls
89 lines (75 loc) · 2.33 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
+(function (window, undef) {
'use strict';
var location = window.location;
var localStorage = window.localStorage;
var XMLHttpRequest = window.XMLHttpRequest;
var proto;
function JSONStorage(root) {
this._root = root;
this._ajax = null;
}
proto = JSONStorage.prototype;
proto.backup = function (data, callback) {
var url = location.href.split('#')[0];
localStorage.setItem(url, JSON.stringify(data));
if (typeof callback === 'function') {
callback(null);
}
};
proto.restore = function (callback) {
var url = location.href.split('#')[0];
if (typeof callback === 'function') {
callback(null, localStorage[url] ? JSON.parse(localStorage[url]) : '');
}
};
proto.link = function (data, callback) {
makeRequest(this, 'data', data, callback);
};
proto.retrieve = function (key, callback) {
makeRequest(this, 'key', key, callback);
};
function makeRequest(self, name, data, callback) {
if (self._ajax) {
self._ajax.abort();
}
self._ajax = new XMLHttpRequest();
self._ajax.name = name;
self._ajax.onreadystatechange = handleRequest.bind(undef, self, callback);
switch (name) {
case 'data':
self._ajax.open('POST', self._root + '.json');
self._ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self._ajax.send(JSON.stringify(data));
break;
case 'key':
self._ajax.open('GET', self._root + '/' + data + '.json');
self._ajax.send();
break;
}
}
function handleRequest(self, callback) {
if (self._ajax.readyState === 4) {
if (self._ajax.status != 200) {
callback(new Error(self._ajax.status));
} else {
var data = self._ajax.responseText.trim();
if (self._ajax.name === 'data') {
data = JSON.parse(data).name;
callback(null, getUrlParts() + '#' + data);
} else if (self._ajax.name === 'key') {
if (!data.length) {
callback(new Error('Unmatched Key: ' + window.location.hash));
} else {
data = JSON.parse(data);
callback(null, data);
}
}
}
self._ajax = null;
}
}
function getUrlParts() {
return (location.protocol + '//' + location.host + location.pathname).split('/');
}
window.JSONStorage = JSONStorage;
}(window));