Skip to content
This repository has been archived by the owner on Mar 13, 2018. It is now read-only.

Commit

Permalink
improve support for default values when using JSON with localstorage
Browse files Browse the repository at this point in the history
  • Loading branch information
Scott J. Miles committed Jan 9, 2014
1 parent cdb4ca5 commit f7f9b9c
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions polymer-localstorage.html
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,29 @@
}
},
load: function() {
var s = window.localStorage.getItem(this.name);
if (s !== null && !this.useRaw) {
try {
this.value = JSON.parse(s);
} catch (x) {
this.value = s;
}
var v = localStorage.getItem(this.name);
if (this.useRaw) {
this.value = v;
} else {
this.value = s;
// localStorage has a flaw that makes it difficult to determine
// if a key actually exists or not (getItem returns null if the
// key doesn't exist, which is not distinguishable from a stored
// null value)
// however, if not `useRaw`, an (unparsed) null value unambiguously
// signals that there is no value in storage (a stored null value would
// be escaped, i.e. "null")
// in this case we save any non-null current (default) value
if (v === null) {
if (this.value !== null) {
this.save();
}
} else {
try {
v = JSON.parse(v);
} catch(x) {
}
this.value = v;
}
}
this.loaded = true;
this.asyncFire('polymer-localstorage-load');
Expand All @@ -100,8 +114,8 @@
* @method save
*/
save: function() {
window.localStorage.setItem(this.name,
this.useRaw ? this.value : JSON.stringify(this.value));
var v = this.useRaw ? this.value : JSON.stringify(this.value);
localStorage.setItem(this.name, v);
}
});
</script>
Expand Down

0 comments on commit f7f9b9c

Please sign in to comment.