jQuery localStorage plugin

I’ve decided to wrap the functionality of HTML5 localStorage in a jQuery plugin, with the simple functionality of a lifetime period for every cache. I’m going to post only the pre-release with the idea to clean up the code in the recent future.

(function(jQuery) {

   var supported = true;
   if (typeof localStorage == 'undefined' || typeof JSON == 'undefined')
      supported = false;
   else
      var ls = localStorage;

   this.setItem = function(key, value, lifetime) {
      if (!supported)
         return false;

      ls.setItem(key, JSON.stringify(value));
      var time = new Date();
      ls.setItem('meta_ct_'+key, time.getTime());
      ls.setItem('meta_lt_'+key, lifetime);
   };

   this.getItem = function(key) {
      var time = new Date();
      if (!supported || time.getTime() - ls.getItem('meta_ct_'+key) > ls.getItem('meta_lt_'+key))
         return false;
      return JSON.parse(ls.getItem(key));
   };

   this.removeItem = function(key) {
      return supported && ls.removeItem(key);
   };

   jQuery.localStorage = this;

})(jQuery);

if (!$.localStorage.getItem('test')) {
   $.localStorage.setItem('test', ['stoimen'], 600000);
   alert('dynamic');
} else {
   alert('from cache');
}

Any feedback is welcome! Yet again the code isn’t tested at all.

Related posts:

  1. jQuery localStorage plugin (alpha)
  2. Storing JavaScript objects in html5 localStorage
  3. clickoutside jQuery plugin
This entry was posted in javascript and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">