-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathofflineApi.js
63 lines (53 loc) · 1.44 KB
/
offlineApi.js
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
/*
* Example of study
* Modelu "Offline Api First", saving requests.
*/
var offlineApi = (function(window, document){
var sendSuperClass = XMLHttpRequest.prototype.send,
openSuperClass = XMLHttpRequest.prototype.open,
offline = true;
/* empty function */
XMLHttpRequest.prototype.offlineSave = function (){};
/*
* Override open function
* save the request in localStorage
*/
XMLHttpRequest.prototype.open = function (type, url) {
var id = Date.now();
mydb.insert('requests', {
id: id,
url: url,
type: type,
data: undefined
});
this.requestId = id;
openSuperClass.apply(this, arguments);
}
/*
* Override send function
* execute and delete the requests in localStorage
*/
XMLHttpRequest.prototype.send = function (data) {
if ( navigator.onLine ) {
mydb.remove('requests', { id: this.requestId });
sendSuperClass.apply(this, arguments);
} else {
mydb.update('requests', { data: data }, { id: this.requestId });
this.offlineSave(this.requestId);
}
}
/*
* Execute requests after the app return to online status
*/
function sync () {
//Send requests for server api.
console.log('Send requests');
console.log(mydb.find('requests', {}));
/* clear collection */
mydb.drop('requests');
}
/*
* Add method sync on event online
*/
window.addEventListener("online", sync, false);
}(window, document));