LocalStorage - Saving complex model

Saves complex object in local storage

by WILLIAM CORREA

HTML

<!-- corresponding blog at http://blog.jardalu.com/2013/6/17/save-complex-object-localstorage-extjs-sencha -->
<title>ExtJs : Saving complex object in localstorage.</title>
<h4>Check the Local Storage (press F12). There should be
an object stored with Key localproxy-1 with the following properties.</h4>
<pre id="example-grid"></pre>

CSS

body {
    padding: 50px 20px 0 20px;
}

JavaScript

Ext.onReady(function () {

    Ext.define('Person', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'Name',
            type: 'string'
        }, {
            name: 'Phones',
            type: 'auto'
        }]
    });

    Ext.define('local.store.localcache', {
        extend: 'Ext.data.Store',
        model: 'Person',
        autoLoad: true,
        proxy: {
            type: 'localstorage',
            id: 'localproxy'
        }
    });


    //save into localstorage
    var cache = new Ext.create('local.store.localcache');
    cache.reload();

    //add to cache if empty
    if (cache.data.length == 0) {

        var person = new Ext.create('Person', {
            Name: 'Bill Clinton',
            Phones: [{
                Number: '123-45-6785'
            }, {
                Number: '123-45-6784'
            }, ]
        });

        //assign after object initialized
        var phones = person.get('Phones');
        phones[phones.length] = {
            "Number": "980-00-9990"
        };

        cache.add(person);
        cache.sync();

    }
    
    var serialized = JSON.stringify(cache.first().data, null, 2);                                       
    new Ext.Component({
        renderTo: 'example-grid',
        html: serialized
    });


});