Skip to main content

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).
1
2
3
4
5
6
7
8
9
10
11
12
// 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:
1
2
3
4
5
6
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
Ext.define('MyApp.util.JsonPStorageProvider', {
    /* Begin Definitions */
 
    extend : 'Ext.state.Provider',
    alias : 'state.jsonpstorage',
 
    config: {
       userId : null,
       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:
1
2
3
4
5
6
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.

Comments

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

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 ( &

EXT JS 4: EMPTY VALUE IN A COMBOBOX

EXT JS 4: EMPTY VALUE IN A COMBOBOX Often, in an Ext JS combobox, it is difficult to go back to an empty value once you have selected an item, particularly if “forceSelection” is set to true.  Here is my roundup of alternative solutions found from around the web… 1. Override beforeBlur The solution from   http://www.sencha.com/forum/showthread.php?182119-How-To-Re-Empty-ComboBox-when-forceSelection-is-Set-To-TRUE  overrides beforeBlur on the combbox to clear out lastSelection.  Here is a copy of the override from the thread: 1 2 3 4 5 6 7 8 9 10 11 12 13 Ext.create( 'Ext.form.field.ComboBox' , {      ...      allowBlank: true ,      forceSelection: true ,      beforeBlur: function (){          var value = this .getRawValue();          if (value == '' ){              this .lastSelection = [];          }          this .doQueryTask.cancel();         this .assertValue();      } }); Or to apply the o