Ben Tracy
Ben Tracy

Reputation: 45

Trouble loading JSON data into a ExtJS datastore

I've tried every combination I can think of in terms of how to configure my ExtJS datastore to read my incoming JSON data. I'm getting this JSON data in:

[{ "data_type": {"attribute1" : "value1",
                  "attribute2" : "value2",
                  "attribute3" : "value3" 
                  }
 },
 { "data_type": {"attribute1": "value4",
                  "attribute2" : "value5",
                  "attribute3" : "value6" 
                  }
 }
]

I don't want to parse the JSON and reformat it in order to make ExtJS happy because it seems redundant. What I want to end up with is a datastore which would allow me to do:

    Ext.create('Ext.container.Container', 
    {
        id: 'junk',
        renderTo: 'slider',
        width: 960,
        height:600,
        layout: 'vbox',
        items: [
           {
              xtype: 'grid',
              title: 'foobar',
              height: 400,
              width: 700,
              store: my_store,
              viewConfig: { emptyText: 'No data' },
              columns: [
                  {
                     text: 'column1',
                     dataIndex: 'attribute1'
                  },{
                     text: 'column2',
                     dataIndex: 'attribute2'
                  },{
                     text: 'column3',
                     dataIndex: 'attribute3'
                  }
              ]
           }
        ]
    }

I know ExtJS knows how to parse this JSON, because I can do:

var foo = Ext.decode(data);
var good_data = foo[0].data_type.attribute1

And that returns 'value1' as I would expect. Can anyone help me understand the magical incantation to get a datamodel and store to do that?

Thanks!

Upvotes: 2

Views: 5926

Answers (1)

Krzysztof
Krzysztof

Reputation: 16150

First of all you should create model:

Ext.define('SomeModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'attribute1'},
        {name: 'attribute2'},
        {name: 'attribute3'}
    ]
});

Then you can configure store to support your data format by setting record property to data_type:

var store = Ext.create('Ext.data.Store', {
    autoLoad: true,
    data : data,
    model: 'SomeModel',
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            record: 'data_type'
        }
    }
});

Working sample: http://jsfiddle.net/lolo/WfXK6/1/

Upvotes: 2

Related Questions