Ext JS 4: Preserving State on the Server

The goal of persisting state between sessions is to allow a user to return to a screen that they had previously customized. Ext JS 4 enables you to save the current state of windows, grids, and panels in a border layout.

Other Ext components can be extended to be state-aware for application specific uses.
Saving state information as browser cookies or into HTML5 localstorage is directly supported by Ext, however, the framework does not include a state provider for storing state information on an application server.

To enable state management you must invoke the Ext.state.Manager.setProvider() method from within your application initialization code. You must also configure a number of component properties that indicate that the object is stateful.

Initializing the Stateful Framework

The first step in enabling the stateful framework is to invoke the Ext.state.Manager.setProvider() method to tell Ext JS where to physically store state information. Typically this is implemented from inside of the app.js launch method as illustrated below, which stores state info as either a browser cookie or into HTML5 LocalStorage, depending on the level of browser support (IE 6/IE 7 do not support localstorage, or anything else that’s even remotely interesting for that matter).

// app.js
launch: function() {
 if (Ext.supports.LocalStorage) {
  Ext.state.Manager.setProvider(
    Ext.create('Ext.state.LocalStorageProvider')
  );
 } else {
  Ext.state.Manager.setProvider(
    Ext.create('Ext.state.CookieProvider')
  );
 }
}

Making a Component Instance Stateful

Instances of Ext.window.Window, Ext.grid.Panel, and Ext.panel.Panel that are contained within a border layout will automatically maintain state so long as you add the stateful:true and stateId: [some id] as illustrated by the following example:

Ext.create('Ext.window.Window', {
 title: 'Hello',
 layout: 'fit',
 stateful: true,
 stateId: 'mystatefulwindow'
}).show();

Every time a user drags, resizes, minimizes, or maximizes the window, state information will be saved out through the designated state provider.

Storing Stateful Information on a Server

Sencha doesn’t provide a mechanism for publishing state information to a webservice, so I thought that I would fill in the gap by creating my own:


Ext.define('MyApp.util.JsonPStorageProvider', {
	/* Begin Definitions */

	extend : 'Ext.state.Provider',
	alias : 'state.jsonpstorage',

	config: {
	   userId : null,
	   url: "http://www.senchatraining.com/ftextjs4/webservices/stateprovider.cfc",
	   timeout: 30000
	},

	constructor : function(config) {
		this.initConfig(config);
		var me = this;

		me.restoreState();
		me.callParent(arguments);
	},
	set : function(name, value) {
		var me = this;

		if( typeof value == "undefined" || value === null) {
			me.clear(name);
			return;
		}
		me.persist(name, value);
		me.callParent(arguments);
	},
	// private
	restoreState : function() {
		var me = this;
		Ext.data.JsonP.request({
			url : this.getUrl(),
			params : {
				userId : this.getUserId(),
				method : 'get'
			},
			disableCaching : true,
			success : function(results) {
				for(var i in results) {
					this.state[i] = this.decodeValue(results[i]);
				}
			},
			failure : function() {
				console.log('failed', arguments);
			},
			scope : this
		});
	},
	// private
	clear : function(name) {
		this.clearKey(name);
		this.callParent(arguments);
	},
	// private
	persist : function(name, value) {
		var me = this;
		Ext.data.JsonP.request({
			url : this.getUrl(),
			params : {
				userId : this.getUserId(),
				method : 'save',
				name : name,
				value : me.encodeValue(value)
			},
			disableCaching : true,
			success : function() {
				// console.log('success');
			},
			failure : function() {
				console.log('failed', arguments);
			}
		});
	},
	// private
	clearKey : function(name) {
		Ext.data.JsonP.request({
			url : this.getUrl(),
			params : {
				userId : this.getUserId(),
				method : 'clear',
				name : name
			},
			disableCaching : true,
			success : function() {
				console.log('success');
			},
			failure : function() {
				console.log('failed', arguments);
			}
		});
	}
});

You can invoke this state provider by using the following syntax:

 Ext.state.Manager.setProvider(
    Ext.create('MyApp.util.JsonPStorageProvider', {
      userId: [a user's login id],
      url: [url to web service where state information will be stored/retrieved]
    })
 );

The state provider will transmit state information about stateful components to your designated webservice using the following URL variables:

userId=[user name or token]
method=clear | save | get
name= [variable name]
value=[url encoded value]

You simply need to create a webservice that stores and retrieves the name/value pairs, and you should be good-to-go.

Happy Hacking!

5 thoughts on “Ext JS 4: Preserving State on the Server

  1. James D

    Can you give examples of the response jsonp that should be returned for a successful ‘save’ or ‘get’ ? I’m having no luck getting this to work

    Reply
  2. sdrucker Post author

    The response for the restorestate function would be something like:

    foo({property1: ‘a’, property2: ‘b’})

    Note that the response is decoded and applied on lines 40-44

    You can simply return an empty string as the response for the persist() method, although the general best practice is to return {success: true}

    Reply
  3. oncethor

    I found a big problem. This won’t always work because, in the restoreState function, the Ext.data.JsonP.request is an async request. The call could return after the grid has read the state.
    You must replace that with something synchronus like:

    restoreState : function() {
    console.log(“calling restoreState”);

    var me = this;
    var response = Ext.Ajax.request({
    async: false,
    url: this.getUrl(),
    params: {
    userId : this.getUserId(),
    method : ‘get’
    }
    });
    //debugger;
    var items = Ext.decode(response.responseText);
    if (items !== undefined) {
    for (var name in items) {
    var temp = this.decodeValue(items[name]);
    me.state[name] = temp;
    console.log(“restored “+name);
    }
    }
    }

    On the server side, using a servlet, you could write:
    } else if (“get”.equals(method)) {
    logger.log(Level.INFO, “CALLED GET!”);
    HashMap records = extJsObjectStates.get(userId);
    if (records == null) {
    records = new HashMap();
    }
    logger.log(Level.INFO, “records={0}”, records);
    response.getWriter().println(mapper.writeValueAsString(records));
    }

    where extJsObjectStates could be:

    static final HashMap<String,HashMap> extJsObjectStates = new HashMap<String,HashMap>();

    and

    import com.fasterxml.jackson.databind.ObjectMapper;
    static final ObjectMapper mapper = new ObjectMapper();

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s