Here’s a simple scenario in your mobile application. You may have to load a collection of cities from the server and display them in a list. When the user accesses the app anytime later, you don’t want to fetch the cities again from the server. Instead, we would like to push the cities in local storage and access them from that storage.
It’s pretty easy to use raw localStorage API and implement it. If you are a Sencha Touch developer, you’ll notice that there are Proxy classes for working with different sources, like ajax, localStorage, sessionStorage etc. So how do we use the same Store class but switch between proxies? Let’s do that. Let’s have two proxies defined as shown below.
var localStorageProxy = { type : "localstorage", id : "name" }; var ajaxProxy = { type : "ajax", url : "Cities", reader : { type : "json", rootProperty : "cities" } };
We’ll define a single store class, say CityStore. We’ll initially wire the localStorageProxy and check if values are present in the local storage. If not, we’ll swap it with the ajaxProxy and fetch the values from the server. Then we’ll swap it with localStorageProxy and store the values in local storage. Here’s the code.
Ext.define("CityStore",{ extend : "Ext.data.Store", config : { fields : ["name"], proxy : localStorageProxy, listeners : { write : function(){ console.log("Successfully Synced to LocalStorage"); }, load : function(storeObj){ var count = storeObj.getCount(); if(count == 0 && storeObj.getProxy() .getInitialConfig("type") != "ajax"){ storeObj.setProxy(ajaxProxy); storeObj.load(); } else{ storeObj.setProxy(localStorageProxy); storeObj.sync(); } } } } });
The load event of the Store class is handled to perform the swapping of proxies.