Here is the scenario: You want need to have some kind of session mechanism, that will allow you to store data across different views in you Ajax application. Let's say you go from form A to form B and there is some data that form B needs from form A, but form A is no longer in the DOM, so you cannot grab it from there. EXTJS has a build session manager, that in the core has two "providers" (storage mechanisms) one just stores the data in JavaScript variable, which in case of reloading the page will get lost, and the other stores the data in a cookie. One of these two "providers" seem to be robust enough (cookies have character limit, and don't seem to be a good storage mechanism for larger data). I decided to take the default Ext.state.Manager provider, and add a "backup" method, that sends the data to the serve, when somebody hits F5, and puts the data back to the JavaScript variable, when the page loads again. (save on unload, retrieve on load)
So enough of theory, here is the is the code:
(function() {
//namespace creation and create local shortcut
var m = Ext.namespace("MyLib.Session");
var settings = {
sessionUrl: "/Ajax/GetSession",
sessionPostUrl: "/Ajax/SetSession"
};
var session = {};
//converts object to string
var objectToString = function(o){
var parse = function(_o){
var a = [], t;
for(var p in _o){
if(_o.hasOwnProperty(p)){
t = _o[p];
if(t && typeof t == "object"){
a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
}
else {
if(typeof t == "string"){
a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
}
else{
a[a.length] = [ p+ ": " + t.toString()];
}
}
}
}
return a;
}
return "{" + parse(o).join(", ") + "}";
};
var saveSession = function(){
var o = session;
var sSession = objectToString(o);
Ext.Ajax.request({
method: "POST",
params: {clientState : sSession},
url: settings.sessionPostUrl
});
}
window.onunload = saveSession;
//load data from the server on load
var loadSession = (function(){
Ext.Ajax.request({
method: "GET",
url: settings.sessionUrl,
success: function(jsonResult) {
//reloads session
session = Ext.decode(jsonResult.responseText);
}
});
})();
//connecting Lib.session to Ext.state.Manager
var provider = function(config){
return{
get : function(name){
return session[name];
},
set : function(name, value){
session[name] = value;
},
clear : function(){
session = {};
}
}
};
//set provider
Ext.extend(provider, Ext.state.Provider, {});
Ext.state.Manager.setProvider(provider());
})();