Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added safeparse to avoid JSON parsing errors screwing up a model

  • Loading branch information...
commit a4c1c522da4026ef990c798da643e1597cbea6d7 1 parent 7c60277
Hunter Loftis authored
Showing with 13 additions and 2 deletions.
  1. +13 −2 backbone.localStorage.js
View
15 backbone.localStorage.js
@@ -50,7 +50,7 @@
if (!this.singleton) {
return _(this.records).chain()
.map(function(id){
- return JSON.parse(this.localStorage().getItem( this.getKey(id) ));
+ return this.safeParse(this.localStorage().getItem( this.getKey(id) ));
}, this)
.compact()
.value();
@@ -67,6 +67,17 @@
}
},
+ safeParse: function(str) {
+ var res;
+ try {
+ res = JSON.parse(str);
+ }
+ catch(e) {
+ res = {};
+ }
+ return res;
+ },
+
// Giving a model a (hopefully)-unique GUID, if it doesn't already
// have an id of it's own.
createId: function(model) {
@@ -110,7 +121,7 @@
// Retrieve a model from `this.data` by id.
find: function(model) {
var key = this.getKey(model.id);
- return key ? JSON.parse(this.localStorage().getItem(key)) : this.getAllRecords();
+ return key ? this.safeParse(this.localStorage().getItem(key)) : this.getAllRecords();
},
// Delete a model from `this.data`, returning it.
Please sign in to comment.
Something went wrong with that request. Please try again.