在Ext-js中为参考对象定义内联数据

时间:2015-03-13 01:32:06

标签: extjs extjs5

如何为其中一个字段为引用的Ext.data.Model内联加载数据?见https://fiddle.sencha.com/#fiddle/ji9

 Ext.define('Address', {
     extend: 'Ext.data.Model',
     fields: ['address', 'city', 'state']
 });

 Ext.define('User', {
     extend: 'Ext.data.Model',
     fields: ['name', {
         name: 'address',
         reference: 'Address'
     }]
 });

 var data = {
     id: 1,
     name: 'Juan',
     address: {
         id: '5',
         address: '22 Main st',
         city: 'Somerville',
         state: 'MA'
     }
 };

var user = new User(data);

// Outputs Address is undefined
console.log('Address is ', user.getAddress().get('city')  );

// Outputs {"id":{"id":"5","address":"22 main st","city":"Somerville","state":"MA"}}
// Instead of {"id":"5","address":"22 main st","city":"Somerville","state":"MA"}
console.log(JSON.stringify( user.getAddress().data ) );

我知道我可以做user.setAddress(new Address(data.address));但我需要一些通用的

1 个答案:

答案 0 :(得分:0)

您可以使用Ext.data.Model's reader来正确创建关联

var user = User.getProxy().getReader().readRecords(data).records[0];
// Outputs Somerville
console.log('Address is ', user.getAddress().get('city')  );

// Outputs {"id":"5","address":"22 main st","city":"Somerville","state":"MA"}
console.log(JSON.stringify( user.getAddress().data ) );