@@ -32,13 +32,7 @@ var PersistentStorage = (function() {
32
32
this . ls = override || LOCAL_STORAGE ;
33
33
34
34
// if local storage isn't available, everything becomes a noop
35
- if ( ! this . ls || ! window . JSON ) {
36
- this . get =
37
- this . set =
38
- this . remove =
39
- this . clear =
40
- this . isExpired = _ . noop ;
41
- }
35
+ ! this . ls && this . _noop ( ) ;
42
36
}
43
37
44
38
// instance methods
@@ -55,6 +49,26 @@ var PersistentStorage = (function() {
55
49
return this . _prefix ( key ) + this . ttlKey ;
56
50
} ,
57
51
52
+ _noop : function ( ) {
53
+ this . get =
54
+ this . set =
55
+ this . remove =
56
+ this . clear =
57
+ this . isExpired = _ . noop ;
58
+ } ,
59
+
60
+ _safeSet : function ( key , val ) {
61
+ try {
62
+ this . ls . setItem ( key , val ) ;
63
+ } catch ( err ) {
64
+ // hit the localstorage limit so clean up and better luck next time
65
+ if ( err . name === 'QuotaExceededError' ) {
66
+ this . clear ( ) ;
67
+ this . _noop ( ) ;
68
+ }
69
+ }
70
+ } ,
71
+
58
72
// ### public
59
73
60
74
get : function ( key ) {
@@ -67,14 +81,14 @@ var PersistentStorage = (function() {
67
81
68
82
set : function ( key , val , ttl ) {
69
83
if ( _ . isNumber ( ttl ) ) {
70
- this . ls . setItem ( this . _ttlKey ( key ) , encode ( now ( ) + ttl ) ) ;
84
+ this . _safeSet ( this . _ttlKey ( key ) , encode ( now ( ) + ttl ) ) ;
71
85
}
72
86
73
87
else {
74
88
this . ls . removeItem ( this . _ttlKey ( key ) ) ;
75
89
}
76
90
77
- return this . ls . setItem ( this . _prefix ( key ) , encode ( val ) ) ;
91
+ return this . _safeSet ( this . _prefix ( key ) , encode ( val ) ) ;
78
92
} ,
79
93
80
94
remove : function ( key ) {
@@ -85,14 +99,7 @@ var PersistentStorage = (function() {
85
99
} ,
86
100
87
101
clear : function ( ) {
88
- var i , key , keys = [ ] , len = this . ls . length ;
89
-
90
- for ( i = 0 ; i < len ; i ++ ) {
91
- if ( ( key = this . ls . key ( i ) ) . match ( this . keyMatcher ) ) {
92
- // gather keys to remove after loop exits
93
- keys . push ( key . replace ( this . keyMatcher , '' ) ) ;
94
- }
95
- }
102
+ var i , keys = gatherMatchingKeys ( this . keyMatcher ) ;
96
103
97
104
for ( i = keys . length ; i -- ; ) {
98
105
this . remove ( keys [ i ] ) ;
@@ -125,4 +132,16 @@ var PersistentStorage = (function() {
125
132
function decode ( val ) {
126
133
return $ . parseJSON ( val ) ;
127
134
}
135
+
136
+ function gatherMatchingKeys ( keyMatcher ) {
137
+ var i , key , keys = [ ] , len = LOCAL_STORAGE . length ;
138
+
139
+ for ( i = 0 ; i < len ; i ++ ) {
140
+ if ( ( key = LOCAL_STORAGE . key ( i ) ) . match ( keyMatcher ) ) {
141
+ keys . push ( key . replace ( keyMatcher , '' ) ) ;
142
+ }
143
+ }
144
+
145
+ return keys ;
146
+ }
128
147
} ) ( ) ;
0 commit comments