Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Last active December 23, 2015 00:29
Show Gist options
  • Save AndrewBarfield/6553607 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/6553607 to your computer and use it in GitHub Desktop.
A cacheable JSON Store using sessionStorage for Ext JS 3.4.x.x
Ext.namespace('COMPANYNAME.data');
COMPANYNAME.data.CacheableJsonStore = Ext.extend(Ext.data.Store, {
storageKeyName: null, // (string) sessionStorage key name
constructor: function (config) {
Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.JsonReader(config)
}));
this.on('beforeload', function (store, options) {
// 1. The client must implement sessionStorage
// 2. The developer must assign a key name to the store
if(!window.sessionStorage || !this.storageKeyName)
return true;
// Avoid a server request/response by retrieving a JSON string from sessionStorage
var jsonData = window.sessionStorage.getItem(this.storageKeyName);
if(!jsonData)
return true;
// Try to construct an object from the JSON string
var jsonObject;
try {
jsonObject = Ext.decode(jsonData);
}
catch(e) {
return true;
}
// Avoid using empty objects created from an empty JSON string
if(!jsonObject)
return true;
// Populate this store with the jsonObject
this.loadData({data: jsonObject});
// Return false to cancel the load() action
return false;
}, this);
this.on('load', function (store, records, options) {
// 1. The client must implement sessionStorage
// 2. The store, records, and data objects must be initialized
// 3. The developer must assign a key name to the store
if (!window.sessionStorage || !store || !records ||
!store.reader.jsonData.data || !this.storageKeyName)
return;
// Do not store data for failed JSON requests
if (store.reader.jsonData.success == false)
return;
// Try to construct a JSON string from the object
var jsonString;
try {
jsonString = Ext.encode(store.reader.jsonData.data);
}
catch(e) {
return;
}
// Do not store empty, null, or undefined JSON "strings"
if(!jsonString)
return;
// Assign the JSON string to the key name in sessionStorage
window.sessionStorage.setItem(this.storageKeyName, jsonString);
}, this);
}
});
Ext.reg('cacheablejsonstore', COMPANYNAME.data.CacheableJsonStore);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment