Working with Ext JS cookies

Tags: sencha, extjs

Tags: extjs, sencha

Using cookies in ExtJS is really easy and straightforward but many people who are new to ExtJS struggle with this.

First of all you need to instantiate the cookie provider and configure the default state provider. In order to control the state, ExtJS provides the singleton Ext.state.Manager which is a global state manager. Cookie provider is implemented with Ext.state.CookieProvider.

Instantiating cookie provider and configure the state provider:

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

Next we can write or read the cookie.

Ext.state.Manager.set('cookie_exp', 'cookieVal');

Ext.state.Manager.get('cookie_exp');

Cookie provider allows to specify some options like, domain, expires, path and secure.

var cookie = new Ext.state.CookieProvider({
    expires: null,
    domain: ‘www.myexample.com’,
    path: ‘/my-ext-lib/’
});

The default value for expires is 7 days. When null is specified the cookie expires when session expires.

The path is the path for which the cookie is active. Default to root. If cookies are used havily in the application it is worth specifing the path overwise skip it. If you spcify the path and later decide to change the folder you should remember to update the path as well.

Having the cookie variable instantiated we can use it:

cookie.set('cookie-hide-warnings', checked);

var hideWarn = cookie.get('cookie-hide-warnings');

If you create a cookie provider you don’t have to configure the state provider unless you use the state provider.

For example you can create a cookie variable and use it:

var cookie = new Ext.state.CookieProvider(){...}

cookie.set('change', 'change2');

cookie.get('change');

but if you use

var change = Ext.state.Manager.get('change');

 

variable change will be undefined because the state provider has not been configured.

Before using it don’t forget to add:

Ext.state.Manager.setProvider(cookie);

Comments

comments powered by Disqus