Sunday 10 March 2013

Understanding Local Storage Proxy in Sencha Touch 2


LocalStorageProxy is available from Sencha Touch 1. LocalStorageProxy uses the new HTML5 localStorage API to save Model data locally on the client browser. HTML5 localStorage API saves data in key and value pairs and doesn't support complex JSON objects.

LocalStorageProxy automatically serializes and deserializes data when saving and retrieving it.

Now, we are going to see how we can store User information in client Browser using HTML5 LocalStorageProxy.

First, lets create a model for User with fields Name, DateOfBirth and Age.

Ext.define('App.model.User', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            {
                name: 'Name'
            },
            {
                name: 'DateOfBirth'
            },
            {
                name: 'Age'
            }

        ]

    }

});


Then, we are going to create a store with Local Storage Proxy configuration and associate 'User' model to the Store.

Ext.define('App.store.User', {
    extend: 'Ext.data.Store',
    requires: [
        'App.model.User'
    ],
    config: {
        model: 'ListApp.model.User',
        storeId: 'UserStore',
        proxy: {
            type: 'localstorage',
            id: 'UserInfo'
       }
    }
});



Now, lets get the registered store by StoreId (defined above) using Ext.getStore().

var UserStore = Ext.getStore('UserStore');

Then, Load the existing data if available from the store using load().

UserStore.load();

Now we are going to add user records to the store Using add().This method will accept model instance as the parameter

UserStore.add({Name:'A Suresh',DateOfBirth:'21-07-1981',Age:'31'});

UserStore.add({Name:'A Suresh123',DateOfBirth:'21-04-1981',Age:'25'});

UserStore.add({Name:'A Suresh456',DateOfBirth:'01-04-1981',Age:'29'});

Finally, sync() method is used to save the records into local storage
UserStore.sync();

Below is the output, When i run the above code in Google Chrome.

You can view this output using Firebug, Click Resources Tab then select "Local Storage" in Left Column


Hope you enjoyed this Post.

No comments:

Post a Comment