forked from jimrhoskins/knockout.localStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknockout.localStorage.js
More file actions
33 lines (26 loc) · 841 Bytes
/
knockout.localStorage.js
File metadata and controls
33 lines (26 loc) · 841 Bytes
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
(function(ko){
// Wrap ko.observable and ko.observableArray
var methods = ['observable', 'observableArray'];
ko.utils.arrayForEach(methods, function(method){
var saved = ko[method];
ko[method] = function(initialValue, options){
options = options || {};
var key = options.persist;
// Load existing value if set
if(key && localStorage.hasOwnProperty(key)){
try{
initialValue = JSON.parse(localStorage.getItem(key))
}catch(e){};
}
// Create observable from saved method
var observable = saved(initialValue);
// Subscribe to changes, and save to localStorage
if(key){
observable.subscribe(function(newValue){
localStorage.setItem(key, ko.toJSON(newValue));
});
};
return observable;
}
})
})(ko);