Search code examples
sencha-touchsencha-touch-2

Build a list from array object sencha touch


I'm new to sencha touch and trying to build a list from an array. I use Ext.data.ArrayStore and having trouble.

My code:

var ListStore = new Ext.data.ArrayStore({       
    autoLoad:myData,    
    autoDestroy: true,
    storeId: 'myStore',
    // reader configs
    idIndex: 0,
    fields: [
       'product',
       {name: 'product', type: 'string'},
       {name: 'id'     , type: 'string'}

    ]       
});

Code of the Panel which includes the list:

var listPanel = new Ext.Panel({
            dockedItems: [{
                xtype: 'toolbar',
                ui: 'light',
                title: 'Product List',
                items: [{
                    text: 'Back',
                    ui: 'back',
                    handler: backHandler
                }]
            }],
            layout: 'fit',
            scroll: 'vertical',
            style: 'background-color:#FFFFF',
            items: [
            {
                xtype:'list',
                store:ListStore,
                itemTpl: '<div class="product"><strong>{product}</strong></div>',
                grouped:true,
                indexBar:true
            }]

Solution

  • First of all, Swar's answer seems perfectly correct. Create a store like that, pass your data as the data config option when creating an Ext.data.Store instance.

    If you've Ext.define()-ed your own store subclass (without a proxy), you can either add the data when you create() your instance, like this:

    Ext.define('MyApp.store.MyStore', {
        extends: 'Ext.data.store',
        model: 'Demo'
    });
    
    myStore = MyApp.store.MyStore({data: arrayOfDemoItems});
    

    Or altertanively, if you already have a store instance (e.g. auto-created by a controller):

    Ext.define('MyApp.controller.MyController',{
        extend: 'Ext.app.Controller',
        stores: ['MyStore'],
        init: function () {
            // You add your items here
            var myStore = this.getMyStoreStore();
            myStore.data.addAll(this.getMyItemsSomehow(););
            // Note that the 'load' event is not fired if you load elements like this,
            // you have to do it manually if you have e.g. a DataView tied to the store:
            myStore.fireEvent('load', myStore);
        },
        getMyItemsSomehow: function () {
            // Return an array of items somehow...
            return [{id: 1, product: 'Spencer'}];
        }
    });