Saturday, August 6, 2011

Sencha Touch offline store

Hello,

This is my first blog post on Sencha Touch. Recently I tried sencha touch and I built an application which can work offline once loaded in browser. Here I will explain how can you get your data offline in sencha touch.

First of all define an offline store with following configuration.


myApp.stores.offlineWordStore = new Ext.data.JsonStore({
    model: 'myModel',
    proxy: {
        type: 'localstorage',
        id: 'myStore'
    }
});

Here is important thing is proxy configuration. It's defined with the type localstorage. When you define proxy with local storage it will use HTML 5 local storage to store data.

Now define your online store as follow.


myApp.stores.onlineWordStore = new Ext.data.Store({
    model: 'myModel',
    proxy: {      
        url: 'http://www.example.com',
        reader: {
            type: 'json',
            root: 'wordset'
        }
    },
    listeners: {
        load: function () {
            Ext.dispatch({
                controller: myApp.controllers.general,
                action: 'setOfflineStore',
                data : this
            });
        }
    }
});

Carefully check load listener, I am calling a function of a controller where I will add all the data of online store to offline store. This is necessary because offline store can not load data directly with configuration like url. Following is the function in controller.


setOfflineStore: function (options) {
        var store = options.data;
        myApp.stores.offlineWordStore.proxy.clear();
       myApp.stores.offlineWordStore.removeAll();
        store.each(function (record) {
                var word = myApp.stores.offlineWordStore.add(record.data)[0];
        });

        myApp.stores.offlineWordStore.sync();
}

That's it and your offline store is ready to work. Now you have to load online store and it will populate data inside offline store.

myApp.stores.onlineWordStore.load();