Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / state / LocalStorageProvider.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.state.LocalStorageProvider
17  * @extends Ext.state.Provider
18  * A Provider implementation which saves and retrieves state via the HTML5 localStorage object.
19  * If the browser does not support local storage, an exception will be thrown upon instantiating
20  * this class.
21  */
22
23 Ext.define('Ext.state.LocalStorageProvider', {
24     /* Begin Definitions */
25     
26     extend: 'Ext.state.Provider',
27     
28     alias: 'state.localstorage',
29     
30     /* End Definitions */
31    
32     constructor: function(){
33         var me = this;
34         me.callParent(arguments);
35         me.store = me.getStorageObject();
36         me.state = me.readLocalStorage();
37     },
38     
39     readLocalStorage: function(){
40         var store = this.store,
41             i = 0,
42             len = store.length,
43             prefix = this.prefix,
44             prefixLen = prefix.length,
45             data = {},
46             key;
47             
48         for (; i < len; ++i) {
49             key = store.key(i);
50             if (key.substring(0, prefixLen) == prefix) {
51                 data[key.substr(prefixLen)] = this.decodeValue(store.getItem(key));
52             }            
53         }
54         return data;
55     },
56     
57     set : function(name, value){
58         var me = this;
59         
60         me.clear(name);
61         if (typeof value == "undefined" || value === null) {
62             return;
63         }
64         me.store.setItem(me.prefix + name, me.encodeValue(value));
65         me.callParent(arguments);
66     },
67
68     // private
69     clear : function(name){
70         this.store.removeItem(this.prefix + name);
71         this.callParent(arguments);
72     },
73     
74     getStorageObject: function(){
75         try {
76             var supports = 'localStorage' in window && window['localStorage'] !== null;
77             if (supports) {
78                 return window.localStorage;
79             }
80         } catch (e) {
81             return false;
82         }
83         //<debug>
84         Ext.Error.raise('LocalStorage is not supported by the current browser');
85         //</debug>
86     }    
87 });
88