-
Notifications
You must be signed in to change notification settings - Fork 1
/
savegame.js
121 lines (102 loc) · 2.83 KB
/
savegame.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
ig.module(
'plugins.savegame'
)
.requires(
'impact.impact'
)
.defines(function() {
ig.Savegame = ig.Class.extend({
localStorageName: 'localStorage',
namespace: '__storejs__',
disabled: false,
init: function(savegameVersion) {
if (typeof savegameVersion == "undefined") {
throw {
name: "VersionNotSet",
message: "You need to set the savegame version.",
toString: function(){return "[ig.Savegame] You need to set the savegame version.";}
}
}
if (this.isLocalStorageNameSupported()) {
this.storage = window[this.localStorageName];
this.set = function(key, val) {
if (val === undefined) return this.remove(key);
this.storage.setItem( key, this.serialize(val) );
return val;
}
this.get = function(key) {
return this.deserialize( this.storage.getItem(key) );
}
this.remove = function(key) {
this.storage.removeItem(key);
}
this.clear = function() {
this.storage.clear();
}
this.getAll = function() {
var ret = {};
for (var i = 0; i < this.storage.length; ++i) {
var key = this.storage.key(i);
ret[key] = this.get(key);
}
return ret;
}
}
try {
this.set(this.namespace, this.namespace);
if (this.get(this.namespace) != this.namespace) {
this.disabled = true;
}
this.remove(this.namespace);
} catch(e) {
this.disabled = true;
}
if (!this.disabled) {
var version = this.get('savegameVersion');
if (version) {
if (version < savegameVersion) {
this.clear();
this.set('savegameVersion', savegameVersion);
}
} else {
this.set('savegameVersion', savegameVersion);
}
}
},
set: function(key, val) {},
get: function(key) {},
remove: function(key) {},
clear: function() {},
getAll: function() {},
transact: function(key, defaultVal, transactionFn) {
var val = this.get(key);
if (transactionFn == null) {
transactionFn = defaultVal;
defaultVal = null;
}
if (typeof val == 'undefined') {
val = defaultVal || {};
}
transactionFn(val);
this.set(key, val);
},
serialize: function(value) {
return JSON.stringify(value);
},
deserialize: function(value) {
if (typeof value != 'string') return;
try {
return JSON.parse(value);
} catch(e) {
return value || undefined;
}
},
isLocalStorageNameSupported: function() {
try {
return (this.localStorageName in window && window[this.localStorageName]);
} catch(e) {
return false;
}
}
});
});