La gestione del web storage in JavaScript può essere semplificata creando un oggetto wrapper.
La soluzione è la seguente:
var Storage = {
type: sessionStorage, // Oppure localStorage
set: function ( item, value ) {
this.type.setItem( item, value );
},
get: function ( item ) {
var value = this.type.getItem( item );
return value;
},
count: function () {
var len = this.type.length;
return len;
},
remove: function ( item ) {
this.type.removeItem( item );
},
empty: function () {
this.type.clear();
},
saveObject: function ( item, obj ) {
if ( typeof obj === "object" ) {
this.set( item, JSON.stringify( obj ) );
} else {
this.set( item, "Could not convert to JSON string" );
}
},
getObject: function ( item ) {
var json = this.get( item );
var obj = JSON.parse( json );
return obj;
}
};