persist associated data
by Johan Vandeplas
HTML
<script src="http://cdn.sencha.io/ext-4.2.0-gpl/ext-all-dev.js"></script>
<link rel="stylesheet" href="http://cdn.sencha.io/ext-4.2.0-gpl/resources/css/ext-all.css">
JavaScript
Ext.onReady(function () {
Ext.define('MyApp.model.Address', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'int'
}, {
name: 'street',
type: 'string'
}, {
name: 'nr',
type: 'int'
}, {
name: 'postcode',
type: 'string'
}, {
name: 'city',
type: 'string'
}]
});
Ext.define('MyApp.model.Person', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.Address'],
fields: [{
name: 'id',
type: 'int'
}, {
name: 'name',
type: 'string'
}, {
name: 'email',
type: 'string'
}, {
name: 'phone',
type: 'string'
}],
hasMany: [
{ model: 'MyApp.model.Address', name: 'address', associationKey: 'address' }
]
});
Ext.define('Ext.data.writer.MyWriter', {
extend: 'Ext.data.writer.Json',
alias: 'writer.mywriter',
allowSingle: false,
persistAssociations: true,
getRecordData: function(record){
var me = this,
rec = me.callParent(arguments),
traverse = function(o,func){
for (i in o) {
func.apply(o,[i,o[i]]);
if (typeof(o[i])=="object") {
//going on step down in the object tree!!
if(o[i] instanceof Ext.data.Model){
o[i] = me.getRecordData(o[i]);
} else {
traverse(o[i],func);
}
}
}
};
if (me.persistAssociations) {
var assocData = record.getAssociatedData(true);
...