JavaScript: salvare lo stato degli oggetti nel web storage

Possiamo salvare lo stato degli oggetti JavaScript nel web storage.

JavaScript di Gabriele Romanato

Possiamo salvare lo stato degli oggetti JavaScript nel web storage.

Consideriamo l'esempio base dell'aggiunta e della sottrazione a e da un totale:


var Order = function() {
    this.total = 0;
    this.init();
};

Order.prototype = {
    init: function() {
        sessionStorage.setItem( "total", this.total );
    },
    save: function( total ) {
        sessionStorage.setItem( "total", total );
    },
    add: function( amount ) {
        this.total = this.total + amount;
        this.save( this.total );
    },
    sub: function( amount ) {
        this.total = this.total - amount;
        this.save( this.total );
    },
    get: function() {
        return sessionStorage.getItem( "total" );
    }
};

In pratica ogni volta che il valore iniziale viene incrementato o decrementato lo salviamo nel web storage. In questo modo ci assicuriamo che il valore dell'oggetto mantenga sempre il suo stato.

Commenti