Sencha Inc. | HTML5 Apps

Using the Data Package in Sencha Touch

Published Aug 17, 2010 | Ed Spencer | Tutorial | Easy
Last Updated Jul 11, 2011

This Tutorial is most relevant to Sencha Touch, 1.x.

One of the core parts of Sencha Touch is the data package. The data package enables applications to persist data through the built in Model, Store and Proxy classes. Most applications will use one or more of these classes, often tied in with the many Store-backed visual components included in Sencha Touch. The root of the data package is Ext.data.Model. Models represent types of data in your application - Users, Products, Sales - anything. Let's imagine we're creating an application to manage products in an ecommerce system - here's how we might set up the Product model:
 
Ext.regModel('Product', {
    fields: [
        {name: 'name',        type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'price',       type: 'float'},
        {name: 'image_url',   type: 'string'},
        {name: 'in_stock',    type: 'boolean'}
    ]
});
 
Ext.regModel tells Sencha Touch to create a new Model with the configured fields. We can later reference this model by name to easily configure components to load Product data. In this example, our application is an HTML5 frontend for our ecommerce site. We want a page to display our products - here's how we might create one using a DataView:
 
var productsList = new Ext.DataView({
    store: new Ext.data.Store({
        model: 'Product',
        proxy: {
            type: 'ajax',
            url : '/products.json',
            reader: {
                type: 'json',
                root: 'products'
            }
        }
    }),
    tpl: new Ext.XTemplate(
        '<tpl for=".">',
            '<div>',
                '<img src="{image_url}" />',
                '<div class="button">Buy</div>',
            '</div>',
        '</tpl>'
    ),
    fullscreen: true
});
 
In the example above we created a Store inside a DataView. A Store is a collection of Model instances, and Stores load their data through a Proxy class. In this example we set up a simple 'ajax' proxy and instructed it to load its data from the url '/products.json'. We also provided a Reader, which tells the Proxy how to decode the response it gets from the server when loading data. In this case, we're expecting the server to return a JSON object, with an array of objects under the 'products' key:
 
{
    "products": [
        {"name": "Some Product",    "price": 9.99, "image_url": "product1.jpg", "in_stock": true},
        {"name": "Another Product", "price": 7.50, "image_url": "product2.jpg", "in_stock": true},
        {"name": "A third product", "price": 2.35, "image_url": "product3.jpg", "in_stock": false},
        ...
    ]
}
 
DataView is a component that knows how to use a Store and render the Model instances to HTML using a template. We set the template above using an Ext.XTemplate - our powerful templating class. Once the Store loads its data, the DataView automatically takes each of the loaded records and renders the HTML for it based on the template, giving us a list of rendered products. Now that we have a rendered page of Products, let's take our example a step further and implement a simple Cart. Our Cart is going to be another Store, this time using the session storage proxy to save the user's cart items client-side until they are ready to proceed:
 
var Cart = new Ext.data.Store({
    model: 'Product',
    proxy: {
        type: 'sessionstorage',
        id  : 'shoppingCart'
    }
});
 
The session storage proxy saves all Model data in the HTML5 sessionStorage object. This means that the products will remain in memory between page refreshes (see our recent Web Storage blog post for more information). The sessionStorage object is shared between all scripts on the same domain so we give the Proxy an id which allows it to store our data in a private namespace. The session storage and local storage proxies don't require readers - all data reading and writing is handled automatically. We can tie a listener to the DataView and add the product to our cart when the user taps the 'Buy' button:
 
productsList.on('itemtap', function(dataview, index, el, e) {
    //the itemtap event is fired whenever any part of the product template is tapped
    //but we only add to the cart if the Buy button was the target
    if (e.getTarget('div.button')) {
        var product = dataview.store.getAt(index);
 
        Cart.add(product);
        Cart.sync();
    }
});
 
We listen for the itemtap event on the DataView, checking that the button div was tapped. If it was we get the product that user tapped on, add it to the Cart Store and sync the store. Calling sync on the Store saves its contents to session storage so that when we refresh the page the contents of our Cart are preserved. This example shows how to quickly put together simple components backed by the data package. We saw how the Model/Store/Proxy ecosystem fits together and how to use Stores with data-aware components. For an example of greater customisation of data package classes see our Twitter example.
Share this post:
Leave a reply

Written by Ed Spencer
Ed Spencer leads the development of Ext JS and Sencha Touch. An expert with Ext JS and JavaScript in general and with several years experience with traditional server side frameworks, he has broad experience in API design and delivery. His passion is in crafting beautiful code that supports the world-class Sencha product line.
Follow Ed on Twitter

10 Comments

akvakv

3 years ago

how can i display Cart Read

akvakv

3 years ago

Could you please let me how to retrieve from a session storage?

akvakv

3 years ago

i want   tpl update tpl

var CartD = new Ext.Panel({
  id: ‘cartDisp’,
           
  tpl: [
                 
  ‘<tpl for=”.”>’,
    ‘

asdasdasd

‘,
    ‘

asdasdasd

‘,
  ‘</tpl>’
  ]
               
  });

JD

3 years ago

What if the request fails or times out? Any way to handle that?

Ed Spencer

3 years ago

@JD yes, check out the ‘load’ event on Ext.data.Store, one of its arguments is a success boolean which tells you if the Operation succeeded or not. The Operation object (which is also attached to the event) contains information about the failure

JD

3 years ago

Thanks Ed. So if I set a timeout of 5 secs, if no response that flag will be false?

Gratis Poker Geld

3 years ago

Hallo , Ik heb genoten van dit project in deze webpagina, sta je met goede informatie! Deze site is veel nuttig !rnIk ben Vera, uit Leicester, en ik + ga een volgeling van deze website zijn, Mijn interesses kun je niet wilt leren kennen , maar ik zeg ze toch ik hou van online poker en sport in het algemeen , en ik luister ook veel Radiohead op mijn slaapkamer , ik ben zonder vriendje op het moment dus jongens kijk uit voor mij .... gewoon flirten met jullie lol smile! Ik heb eens geprobeerd online dating Het werkte niet heel goed ....rnIk schreef dit commentaar veroorzaken zoals ik al zei dat ik echt genieten van uw blog heb ik ook een blog hebben net als u, maar de mijne is een beetje anders is het over poker te spelen zonder een storting te maken ....smilernIk zal ook excuses van mijn taal was het de enige manier waarop ik vond om te communiceren met je ....rnGoedenavond iedereen , Bye

Gratis Poker Geld

3 years ago

Hallo , Ik heb genoten van dit project in deze webpagina, sta je met goede informatie! Deze site is veel nuttig !rnIk ben Vera, uit Leicester, en ik + ga een volgeling van deze website zijn, Mijn interesses kun je niet wilt leren kennen , maar ik zeg ze toch ik hou van online poker en sport in het algemeen , en ik luister ook veel Radiohead op mijn slaapkamer , ik ben zonder vriendje op het moment dus jongens kijk uit voor mij .... gewoon flirten met jullie lol smile! Ik heb eens geprobeerd online dating Het werkte niet heel goed ....rnIk schreef dit commentaar veroorzaken zoals ik al zei dat ik echt genieten van uw blog heb ik ook een blog hebben net als u, maar de mijne is een beetje anders is het over poker te spelen zonder een storting te maken ....smilernIk zal ook excuses van mijn taal was het de enige manier waarop ik vond om te communiceren met je ....rnGoedenavond iedereen , Bye

Dan Nugent

3 years ago

Great article! I’ve been looking for a solution like this for a while.

One newby question: Once the data collected is in localstorage, how do I get it back into my server?

Vita Tänder

3 years ago

Very useful info, thanks ed! I’ve seen your other site as well edspencer.net, I’d say your tutorials are good reference, and it work!s Thanks!

Leave a comment:

Commenting is not available in this channel entry.