日期:2014-05-16  浏览次数:20362 次

sencha2.0 接受多层json数据和使用association的model
使用sencha接受多层的json数据是很常见的,比如:
[{
    "code":"Kobechris",
    "total":"Bryant2",
    "message":"http:\/\/192.168.1.20\/mobile_ajax\/images\/frontpage.jpg",
    "result":[{"label":"ahouse2"},{"label":"bhouse22"}]
},{
    "code":"Kobe",
    "total":"Bryant",
    "message":"http:\/\/192.168.1.20\/mobile_ajax\/images\/frontpage.jpg",
    "result":[{"label":"chouse1"},{"label":"dhouse11"}]
}]

上例中result就有多一层的json结构数据,但是sencha的一个model只接受一层的数据,那如何接受第二层的数据呢。

那么就要使用到另外一个model来定义下一层的json数据了,比如,我们定义一个model名为PropertyList来接受第一层,比如上例中的code,total,message;在定义一个model名为Property来接收第二层的数据,比如上例中result中的label;详细代码如下:

第一个model文件(PropertyList),

Ext.define('app.model.PropertyList',{
    extend: 'Ext.data.Model',
    requires: [
    	'app.model.Property',
    ],

    config: {
        fields: [
	        {name : 'code',        	type : 'string'},
	        {name : 'message',		type : 'string'},
		{name : 'total',		type : 'string'},
        ],
        associations: [{
        	type: 'hasMany', 
        	model: 'app.model.Property', 
        	name:'result', 
        	associationKey:'result'
        }]
    }
});
有人说可以使用
hasMany: {model: 'app.model.Property', name: 'result'}
来代替association,这的确在sencha的开发文档中都出现过,但是文档中也说明这是associations的简短缩略,以至于有很多字段都没能指明,总之我用起来就达不到效果,所以我习惯使用完整的associations。

另一个model文件(Property),

Ext.define('app.model.Property',{
    extend: 'Ext.data.Model',

    config: {
        fields: ['label'],
    }
});
这个文件只是迎合上一个PropertyList的model文件,是最底层的json,所以很普通就可以了。

可以定义一个store文件来接受PropertyList的model数据了,如PropertyList.js文件

Ext.define('app.store.PropertyList',{
	extend : 'Ext.data.Store',
	requires: [
            'Ext.data.proxy.JsonP'
        ],
	config : {
	    model : 'app.model.PropertyList',
            autoLoad: true,
            sorters: 'code',
            pageSize: 10,
            grouper: {
                groupFn: function(record) {
                    var result = record.get('result');
                    for(var i in result){
                        var res = result[i].label;
                        return res[0];
                    }
                }
           },
           proxy: {
               type: 'jsonp',
               url: 'http://127.0.0.1/test.php'
           }
	}
});

于是只要在头文件app.js里的models和stores里引入相应的PropertyList就可以了。

后记:

也可以把两个model文件放到同一个文件里,如

Ext.define('app.model.PropertyList',{
    extend: 'Ext.data.Model',
    requires: [
    	//'app.model.Property',
    ],

    config: {
        fields: [
	        {name : 'code',        	type : 'string'},
	        {name : 'message',		type : 'string'},
		{name : 'total',		type : 'string'},
        ],
        associations: [{
        	type: 'hasMany', 
        	model: 'Property', 
        	name:'result', 
        	associationKey:'result'
        }]
    }
});
Ext.define('Property',{
    extend: 'Ext.data.Model',

    config: {
        fields: ['label'],
    }
});

1楼dats04074天前 18:39
也可以把两个model放在同一个文件里面