I\'m creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
(function($){
I'm a fan of the pattern I've seen on Eric Martin's SimpleModal. This works well for when I'm NOT acting on DOM elements -- in this case a wrapper to utilize localStorage.
This way I can easily refer to the constructor:
$.totalStorage('robo', 'cop');
...or a public method:
$.totalStorage.getItem('robo'); //returns 'cop'
Here's the internals:
;(function($){
/* Variables I'll need throghout */
var ls;
var supported = true;
if (typeof localStorage == 'undefined' || typeof JSON == 'undefined') {
supported = false;
} else {
ls = localStorage;
}
/* Make the methods public */
$.totalStorage = function(key, value, options){
return $.totalStorage.impl.init(key, value);
}
$.totalStorage.setItem = function(key, value){
return $.totalStorage.impl.setItem(key, value);
}
$.totalStorage.getItem = function(key){
return $.totalStorage.impl.getItem(key);
}
/* Object to hold all methods: public and private */
$.totalStorage.impl = {
init: function(key, value){
if (typeof value != 'undefined') {
return this.setItem(name, value);
} else {
return this.getItem(name);
}
},
setItem: function(key, value){
if (!supported){
$.cookie(key, value);
return true;
}
ls.setItem(key, JSON.stringify(value));
return true;
},
getItem: function(key){
if (!supported){
return this.parseResult($.cookie(key));
}
return this.parseResult(ls.getItem(key));
},
parseResult: function(res){
var ret;
try {
ret = JSON.parse(res);
if (ret == 'true'){
ret = true;
}
if (ret == 'false'){
ret = false;
}
if (parseFloat(ret) == ret){
ret = parseFloat(ret);
}
} catch(e){}
return ret;
}
}})(jQuery);