JavaScript

Small lib to save in localStorage


var storage= {
  setItem: function(key, val) {
   if (!val) { val  = null; return;}
 if (typeof val == "object") {
 val = JSON.stringify(val); // type casting object into string
 }
 localStorage.setItem(key, val);
 },
 getItem: function(key) {
 var val = localStorage.getItem(key);

 if (!val) {return;}

 // parsing stringified object back to object
 len = val.length;
 if (val[0] == "{" && val[len-1] == "}") {
 val = JSON.parse(val);
 }

 return val;
 }
}

// TESTING IN CONSOLE.

storage.setItem("ID",{name:"Jumper"});
var id = storage.getItem("ID");
console.log("name : "+id.name);


Advertisements

1 thought on “Small lib to save in localStorage”

  1. Hi, I do believe this is a great web site. I stumbledupon it 😉 I’m going to return yet again since I book marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s