Permalink
Browse files

Add a way to save & fetch a model's attributes to/from local storage.

  • Loading branch information...
1 parent 9077c72 commit 71d4bea94ed2b822d8efae09d1f2e0a657ace1fd @fblee fblee committed May 16, 2012
Showing with 35 additions and 0 deletions.
  1. +35 −0 js/lib/saveable.js
View
@@ -0,0 +1,35 @@
+/*global lib, JSON */
+lib.saveable = function (_public, _protected, key) {
+ if (!JSON) {
+ throw new Error("JSON does not exist");
+ }
+
+ _public.save = function () {
+ return lib.storage.setItem(key, JSON.stringify(_public.attributes()));
+ };
+
+ _public.fetch = function () {
+ var data = lib.storage.getItem(key);
+ if (data) {
+ data = JSON.parse(data);
+ }
+ return data;
+ };
+
+ _public.loadWithDefaults = function (initialData) {
+ var saved = _public.fetch();
+
+ if (saved) {
+ _public.attributes(saved);
+ } else {
+ _public.attributes(initialData);
+ _public.save();
+ }
+ };
+
+ _public.clearStorage = function () {
+ lib.storage.setItem(key, undefined);
+ };
+
+ return _public;
+};

0 comments on commit 71d4bea

Please sign in to comment.