Blog Archive

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


12 comments :

  1. hey thanx for this tutorial. but its not running in my case. i had just changed view file by creating grid in EmployeeList.js file. My new view code for this file is
    Ext.define('myApp.view.EmployeeList' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.employeeList',

    title : 'Grid',



    initComponent: function() {

    this.store = 'Employees';

    this.columns = [{
    text : 'name',
    flex : 1,
    sortable : false,
    dataIndex: 'name'
    },
    {
    text : 'department',
    sortable : true,
    dataIndex: 'department'
    },
    {
    text : 'age',
    dataIndex: 'age'

    }

    ] }
    });
    But this example is not running. its giving error as 'Uncaught TypeError: Cannot call method 'getProxy' of undefined '
    Can please anyone suggest me what modifications are needed?

    ReplyDelete
    Replies
    1. I think you are mixing Sencha Touch with ExtJs. If you need local storage example for
      ExtJs then review the following example

      http://www.mysamplecode.com/2012/06/extjs-local-storage-example.html

      Delete
  2. Nice post keeps on posting this type of interesting and informative articles.

    ReplyDelete
  3. Hey It's cuming for my case Ext is not defined.

    ReplyDelete
  4. Thanks .. for such a great tutorial... :)

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Thx Can you post remove or delete button when ı select item

    ReplyDelete

  7. The share your really gives us excitement. Thanks for your sharing. If you feel tired at work or study try to participate in our games to bring the most exciting feeling. Thank you!
    hotmail sign in | red ball game | 192.168.1.1

    ReplyDelete