Sencha Touch Local Storage Example

How to use Local Storage and Session Storage to save application data in Sencha Touch

In addition to cookies HTML5 supports storing client data in Web Storage such as Local Storage and Session Storage. Session storage as the name suggest only pertains to that browser session and Local Storage is kind of permanent. Local Storage is extremely useful for storing client specific data on the client device for faster and more secure access. Sencha Touch LocalStorageProxy makes it easy to save and retrieve complex JSON data as it automatically serializes and deserializes the Model data. In this example we have create a store that uses localstorage as proxy to save a list if employees locally and lets the user add and edit the information.


Sencha touch local storage example
Sencha touch local storage example

Application HTML source - index.html

<!DOCTYPE html>
<html>
<head>
<title>Sencha Touch Local Storage Example</title>
<link rel="stylesheet"
 href="sencha-touch/resources/css-debug/sencha-touch.css"
 type="text/css">
<script type="text/javascript"
 src="sencha-touch/sencha-touch-all-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>

Application JavaSript source - app.js

Ext.Loader.setConfig({ 
 enabled: true 
});

Ext.application({
    
 name: 'myApp',
 appFolder: 'app',
 
 requires: [
               'myApp.view.EmployeeList',
               'myApp.view.EmployeeEdit'
               ], 
               
    views : ['EmployeeList'],           
    controllers: ['EmployeeMaster'],
    
    launch: function() {
     console.log('Application launch');
     Ext.create('Ext.Container', {
      fullscreen: true,
      layout: 'vbox',
         items: [{
                xtype : 'toolbar',
                docked: 'top',
                items: [{
                         xtype: 'button',
                            itemId: 'addEmployee',
                            text: 'Add an Employee',
                            iconCls: 'arrow_right',
                            iconMask: true, 
                        }
                      ]
            },{
          flex: 1,
          xtype: 'employeeList'
            }]
     });
    }
    
});

Product Model Representation - Employee.js

Ext.define('myApp.model.Employee', {
    extend: 'Ext.data.Model',
    config: {
     fields: [
    'name',
    'department',
    'age'
    ]
    }
});

Store proxy set to Local Storage - Employees.js

Ext.define('myApp.store.Employees', {
    extend: 'Ext.data.Store',
    
    config: {
     model: 'myApp.model.Employee',
     autoLoad: true,
     
     proxy: {
      //use sessionstorage if need to save data for that
      //specific session only
      type: 'localstorage',
         id  : 'myEmployeeKey'
     }
    }
});

Display List of Employees - EmployeeList.js

Ext.define('myApp.view.EmployeeList', {
    extend: 'Ext.dataview.List',
    alias : 'widget.employeeList',
    
    config: {
     store : 'Employees',
     emptyText : 'Currently there are no Employees, please ADD!',
     
     itemTpl: '<div class="myContent">'+ 
       '<div>Name: <b>{name}</b></div>' +
       '<div>Department: <b>{department}</b> Age: <b>{age}</b></div>' +
       '</div>'
    
    } 
});

Employee Information Add/Edit Panel - EmployeeEdit.js

Ext.define('myApp.view.EmployeeEdit', {
    extend: 'Ext.form.Panel',
    alias : 'widget.employeeEdit',
    
    config: {
     
     // We give it a left and top property to make it floating by default
        left: 0,
        top: 0,

        // Make it modal so you can click the mask to hide the overlay
        modal: true,
        hideOnMaskTap: true,

        // Set the width and height of the panel
        width: 400,
        height: 230,
     layout: {
            type: 'vbox',
        },
        defaults: {
            margin: '0 0 5 0',
            labelWidth: '30%'
        },
        items: [
            {
       xtype: 'textfield',
       name: 'name',
       label: 'Name',
       itemId: 'employeeName' 
   },   
   {
       xtype: 'selectfield',
       itemId: 'department',
       name: 'department',
       label: 'Department',
       options: [
           {text: 'Marketing',  value: 'Marketing'},
           {text: 'Sales', value: 'Sales'},
           {text: 'Tech',  value: 'Tech'},
           {text: 'Administration',  value: 'Administration'}
       ]
   },   
   {
                xtype: 'numberfield',
                label: 'Age',
                name: 'age',
                itemId: 'age' 
            },    
   {
                xtype: 'button',
                itemId: 'save',
                text: 'Save'
            }
            
        ]
    }
  
});

Application controller source - EmployeeMaster.js

Ext.define('myApp.controller.EmployeeMaster', {
 extend : 'Ext.app.Controller',

 config: {
  profile: Ext.os.deviceType.toLowerCase(),
  stores : ['Employees'],
  models : ['Employee'],
  refs: {
   myEmployeeList: 'employeeList'
  },
  control: {
   'employeeList': {
    activate: 'onActivate',
    itemtap: 'onSelectEmployee'
   },
   'container button[itemId=addEmployee]' : {
    tap : 'onAddEmployee' 
   },
   'employeeEdit button[itemId=save]' : {
    tap : 'onSaveEmployee' 
   }
  }  

 },

 onActivate: function() {
  console.log('Main container is active');
 },

 onAddEmployee: function(button) {
  console.log('Button Click');
  var employeeForm = Ext.Viewport.down('employeeEdit');
  //create the employee edit window if it doesn't exists
  if(!employeeForm){
   employeeForm = Ext.widget('employeeEdit');
  } 
  employeeForm.reset();
  employeeForm.showBy(button);

 },

 onSaveEmployee: function(button) {
  console.log('Button Click for Save');
  var form = button.up('panel');
  //get the record 
  var record = form.getRecord();
  //get the form values
  var values = form.getValues();
  //if a new employee
  if(!record){
   var newRecord = new myApp.model.Employee(values);
   Ext.getStore('Employees').add(newRecord);
  }
  //existing employee
  else {
   record.set(values);
  }
  form.hide();
  //save the data to the Web local Storage
  Ext.getStore('Employees').sync();

 },

 onSelectEmployee: function(view, index, target, record, event) {
  console.log('Selected an Employee from the list');
  var employeeForm = Ext.Viewport.down('employeeEdit');

  if(!employeeForm){
   employeeForm = Ext.widget('employeeEdit');
  } 
  employeeForm.setRecord(record);
  employeeForm.showBy(target);
 }

});

References

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.