PDA

View Full Version : Ext.ux.state.LocationHashProvider



tonextone
30 Jun 2008, 8:14 AM
I created a simple custom state.Provider which saves state into location.hash.

You will get the 'stateful' URL with location.hash, for example



http://yourhost.com/path/to/app#(state data encoded)


You can save it as bookmark, email it to your friend, or whatever you want.

# Yes, I am not sure this naming 'state.Provider' is suitable, but anyway it may be useful for some case.



/**
* Ext.ux.state.LocationHashProvider which saves state into location.hash .
*
* @author master@tonextone.com
* @copyright (c) 2008, by master@tonextone.com .
* @date 23 April 2008
*
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
*/

Ext.namespace("Ext.ux.state");

/**
* @class Ext.ux.state.LocationHashProvider
* @extends Ext.state.Provider
* Our custom Provider implementation which saves state into location.hash.
* <br />Usage:
<pre><code>
Ext.state.Manager.setProvider(new Ext.ux.state.LocationHashProvider({}));
</code></pre>
* @constructor Create a new LocationHashProvider
* @param {Object} config The configuration object
*/

Ext.ux.state.LocationHashProvider = function(config){
Ext.ux.state.LocationHashProvider.superclass.constructor.apply(this, arguments);
Ext.apply(this, config);
this.state = this.getState();
};

Ext.extend(Ext.ux.state.LocationHashProvider, Ext.state.Provider, {

// public
set: function(name, value){
if(typeof value == "undefined" || value === null){
this.clear(name);
return;
}
this.addToLocationHash(name, value);
Ext.ux.state.LocationHashProvider.superclass.set.apply(this, arguments);
},

// public
clear: function(name){
this.removeFromLocationHash(name);
Ext.ux.state.LocationHashProvider.superclass.clear.apply(this, arguments);
},

// private
getState: function(){
var locationHash = document.location.hash.replace(/^#/, '');
if (!locationHash) return {};
var state = Ext.decode(decodeURI(locationHash));
return state ? state : {};
},

// private
addToLocationHash: function(name, value){
var state = this.getState();
state[name] = value;
document.location.hash = encodeURI(Ext.encode(state));
},

// private
removeFromLocationHash: function(name){
var state = this.getState();
delete state[name];
document.location.hash = encodeURI(Ext.encode(state));
}

});

mrsunshine
16 Dec 2008, 4:30 AM
Nice work :), Thank you

one question:
why do you use the JavaScript Function

encodeURI()
instead of

Ext.urlEncode()

regards
nils

tonextone
7 Feb 2009, 11:04 PM
nils,
thank you for your interest.

As for Ext.urlEncode(), it is totally different from encodeURI().

Ext.urlEncode() is something like "Object.toQueryString()".
while encodeURI() is exactly for URI-encoding.

http://en.wikipedia.org/wiki/Percent-encoding

regards,
tonextone

smartree
19 Jun 2010, 9:32 AM
Why not save it to Server.