Print Shortlink

Local storage with Ext JS 4

Local storage in HTML 5 lets you store data in the browser’s memory. Unlike cookies they don’t travel with the client request. Mobile applications make use of this facility extensively. Playing with local storage in the raw format using JavaScript can get tedious if the data that you’re trying to store has a complex structure. You may have to put in effort to format the data before and after storing, work with the conversion mechanisms etc.,

Ext JS4’s API makes working with local storage absolute breeze due to the serialization and deserialization facilities it provides. You can create a complex object and save it in local storage, retrieve it and operate on it without any hassles or extra effort.

Let’s define a Model called User with id, username and password fields. The proxy of this Model will point to localstorage. You have to specify an unique identifier to the proxy, for it identify the data in local storage. Let’s define the identifier as ‘credentials’.

Ext.define("User",{
		extend : "Ext.data.Model",
		fields : [
		          	"id","username","password"
		         ],
		proxy : {
				type : "localstorage",
				id : "credentials"
			}         
}); 

Let’s create an instance of the User Model and save it. We’ll implement this conditionally ie., save it only when the credentials are not available, else display the user name.

Ext.application({
		launch : function(){
		  User.load(101,{
			   callback: function(record){
					if(record.get("id") != 101){
					var user1 = Ext.create("User",{id:101,username:"admin",password:"admin"});
					user1.save(); 
					alert("User created successfully");		
				}
				else{
					alert("User name : " + record.get("username"))
				}
			}
		  });
		}
	     });

The static method load and the instance method save are used in the code above. The save method automatically serializes the user object and saves it. The load deserializes the data and gives it to you as the Model instance. The snapshot of the local storage in Google chrome is shown below.

The local storage section has a key “credentials” that lists the id of all the objects stored. You will also have the individual objects stored with the key format roughly equivalent to “credentials-idNumber”.

Leave a Reply