Nick Div
Nick Div

Reputation: 5628

How to set data to List in Sencha Touch from the JSON Object

I want to set Data to a Dataview.list in a controller from a JSON Object.

Here is the json object

Object {1: "Mercedes", 2: "Aston Martin", 3: "Ferrari", 4: "Lamborgini"}

Now this is what I found in the docs:

Ext.create('Ext.List', {
    fullscreen: true,
    itemTpl: '{title}',
    data: [
        { title: 'Item 1' },
        { title: 'Item 2' },
        { title: 'Item 3' },
        { title: 'Item 4' }
    ]
});

This does not work for me as I have the data coming from a JavaScript function. The function returns me the JSON Object mentioned above and then I want to do "setData"

Any ideas?

Any help would be appreciated.

Upvotes: 0

Views: 363

Answers (1)

Apoorv Nag
Apoorv Nag

Reputation: 1279

We can try to convert the object json into an array first. Then we can set the array to the data of the list view or data view.
Refer the code below. It works.

Ext.define('ListDemo.view.Main', {
    extend: 'Ext.Panel',
    xtype: 'main',
    requires: [
    'Ext.dataview.List'
    ],
    config: {       
        height:'900px',
        items: [
            {
                xtype:'list',
                height: '100%',
                itemTpl: 'Hi {title}',
                
                listeners:{
                    painted:function(){
                        var data=Ext.Object.getValues(myspace.obj);
                        var arr=[]
                        for(var i=0;i<data.length;i++){
                            arr.push({cars:data[i]})
                        }
                        Ext.ComponentQuery.query('list')[0].setItemTpl('{cars}')
                        Ext.ComponentQuery.query('list')[0].setData(arr)
                    }
                }
            }
        ]
    }
},function  () {
    Ext.ns('myspace');
    myspace.obj= {1: "Mercedes", 2: "Aston Martin", 3: "Ferrari", 4: "Lamborgini"} 
});

Upvotes: 0

Related Questions