Skip to main content

Creating an auto-caching Data Store in Sencha Touch and Ext JS 4

Here’s a flexible auto-caching data store.
Develop it using Sencha Architect.
1) Add a Store to your project
2) In the project inspector, click the [+] adjacent to functions to define the constructor, isCacheMiss, setCacheExpiration, and applyLocalStorageProxy functions.
3) To define the configs (remoteProxy, localStorageProxy, etc), type the name:value pairs directly into the Config panel’s search box and press the Add button. Once the property has been added to the config panel, you can click on the button to the left of the config property to set its data type (string, object, array)

Data read in from a remote proxy is automatically saved out into localstorage.
Two different caching schemes are supported.

//
// Auto-caching store. Auto-caches data in localstorage.
//

// Scenario 1: Usage with time-based caching:
// Cache data for 1 day
//
// Ext.create('MyApp.store.CachedStore', {
//   extend: 'MyApp.store.LocalCache',
//   storeId: 'PatientEdReports',
//   proxy: {
//     type: 'ajax',
//     url: 'data/mydata.json'
//   },
//   strategy: {
//    type: 'timeout',
//    duration: {'d' : 1}
//   }
// });
//

//
// Scenario 2: Usage with token-based caching
// Cache until lastUpdated token changes
//
// Ext.create('MyApp.store.CachedStore', {
//   extend: 'MyApp.store.LocalCache',
//   storeId: 'PatientEdReports',
//   proxy: {
//     type: 'ajax',
//     url: 'data/mydata.json'
//   },
//   lastUpdated: '2013-02-10 08:00:00 -08:00'
// });
//

Ext.define('MyApp.store.LocalCache', {
 extend: 'Ext.data.Store',

 requires: [
   'Ext.device.Connection',
   'Ext.data.proxy.LocalStorage',
   'Ext.DateExtras'
 ],

 config: {
   remoteProxy: { },
   localStorageProxy: { },
   lastUpdated: '2013-04-02 06:36:00 -8:00',
   strategy: { type: 'token' },
   storeId: 'MyStore'
 },

 constructor: function(config) {
   this.callParent(arguments);

   this.expireField = Ext.app.Application.appInstance.getName() + "-" + this.getLocalStorageProxy().id + '-lastupdated';

   if (Ext.Object.getSize(this.getRemoteProxy()) == 0)
    this.setRemoteProxy(this.getProxy().getInitialConfig());

   // todo - sync when browser comes online
   // note that this event doesn't fire in desktop browser
   // Ext.device.Connection.on('onlinechange',this.setConnection, this);
 },

 load: function(options, scope) {
  var online = Ext.device.Connection.isOnline();

  var me = this;
   
  if (online && this.isCacheMiss()) {
    this.setProxy(this.getLocalStorageProxy());

    // load from localstorage
    this.callParent([{
     scope: this,
     callback: function() {
       // delete from local storage
       this.removeAll();
       this.sync();

       // load from server
       this.setProxy(this.getRemoteProxy());

       // get pointer to superclass load method
       // note that this.callParent() will not work
       // from this context

       var  method=this.callParent.caller;
       var loader = method.$owner.superclass[method.$name];

       // invoke super.load() and write remote data to localstorage
       loader.call(this,{
          scope: this,
          callback: function(records,operation,success) {
            me.setProxy(this.getLocalStorageProxy());
            for (var i=0; i
              records[i].setDirty();
            }             
            me.sync(); // write to localstorage
            me.setCacheExpiration();

            // perform optional final callback
            options = options || {};

            if (Ext.isFunction(options)) {
              options = {
               callback: options,
               scope: scope || this
              };
             }

            if (options.callback) {
              options.callback.call(options.scope,
                                    records,
                                    operation,
                                    success
              );
            }
        } // callback
      }); // load
     } 
    }]);

   } else {
     this.setProxy(this.getLocalStorageProxy());
     this.callParent(arguments);
   }
}, // end function


 isCacheMiss: function() {
    // use date as a default
    var expiry = window.localStorage.getItem(this.expireField);
    if (expiry === null) {
      return true;
    }

    switch(this.getStrategy().type) {
     case 'token' :
       return !(expiry == this.getLastUpdated());

     case 'timeout' :
       var timeout = Ext.Date.parse(expiry,"Y-m-d H:i:s P");
       return (new Date() > timeout);
    }
},


setCacheExpiration: function() {

  switch(this.getStrategy().type) {
    case 'token' :
     window.localStorage.setItem(this.expireField, this.getLastUpdated());
     break;

     case 'timeout' :
      var expireDate = new Date();
      var duration = this.getStrategy().duration;
      for (var i in duration) {
        expireDate = Ext.Date.add(expireDate,i,duration[i]);
      }
      var timeout = Ext.Date.format(expireDate,"Y-m-d H:i:s P");
      window.localStorage.setItem(this.expireField, timeout);
      break;
   }
 },

 applyLocalStorageProxy: function(newObj,oldObj) {

    if (Ext.Object.getSize(newObj) == 0) {
           // set default proxy based on storeid
       newObj = {type: 'localstorage', id: Ext.app.Application.appInstance.getName() + "-" + this.getStoreId()};
       return newObj;
    } else {
      return newObj;
    }
 }
});

Comments

Post a Comment

Popular posts from this blog

ExtJS - Grid panel features

What can we do with ExtJS GridPanel? I have to develop a lot of applications in my web app and I see that grid component of ExtJS may fit in. However, I am not aware of what all things I can do with the - off the shelf available framework pieces - available plug-ins in the marketplace and - custom development through my own developers This is a typical question that we hear from the business users who wants to design an application by keeping the framework’s capability in perspective. In this article I have tried to put the list of stuff you can do with grid and hopefully that shall enable you to take advantage of the beauty of ExtJS. Pre-requisites This article assumes that you are familiar with basics of ExtJS What are the available options? In this section I will be taking you through some of the commonly seen usage of ExtJS grid panel. While covering all the capabilities of grid may not be possible, I am sure it will be helpful for the business users who want to...

ExtJS 4 with Spring MVC Example

Introduction When developing a brand new application for the company I work for, one of the first thing I implement is "authentication". Not only is this process generally a prerequisite to access many other functions but it is also very simple and covers every layer of an application, from GUI to the database. So instead of another minimalistic "Hello World" tutorial, here is a "Login/Password" example, using 2 famous technologies : Spring MVC and ExtJS 4.   Prerequisites Because this tutorial is quite long, I won't go into the details of each technology I used but I will mainly focus on how ExtJS and Spring can be nicely used together. So here are the things you should know before continuing : Spring framework (good knowledge) Spring MVC (basic knowledge. See  Spring MVC Official Documentation  for details) ExtJS "application architecture" (see  Sencha Docs  for details) Eclipse IDE + Tomcat 6 (or any other web container) You a...

Ext4 Apply Store Filtering

In extjs4.1: There are many way for store filtering . Some of code i give here Filtering by single field: store . filter ( 'eyeColor' , 'Brown' );   Alternatively, if filters are configured with an  id , then existing filters store may be  replaced by new filters having the same  id . Filtering by single field: store . filter ( "email" , /\.com$/ );   Using multiple filters: store . filter ([ { property : "email" , value : /\.com$/ }, { filterFn : function ( item ) { return item . get ( "age" ) > 10 ; }} ]);   Using  Ext.util.Filter  instances instead of config objects (note that we need to specify the root config option in this case): store . filter ([ Ext . create ( ' Ext.util.Filter ' , {   property : "email" , value : /\.com$/ , root : 'data' }),   Ext . create ( ' Ext.util.Filter ' , {   filterFn : function ( item ) {   return item . get ( ...