dimanche 8 juin 2014

Grouped list with nested hasMany data

What's the best way to make a list from associated models? I've read quite a few people trying to do this, but every solution seems very hacky, if it works at all. For example, with this data:

Code:



crews: [
{
id: 1,
name: 'Steve',
jobs: [
{
id: 102,
type: 'Cleanup'
},
{
id: 103,
type: 'Rails'
}
]
},
{
id: 2,
name: 'Rick',
jobs: [
{
id: 116,
type: 'Frame'
}
]
}
]

I want a list of all jobs , but group them by crew name.

Code:



Ext.define('Crew',{
extend: 'Ext.data.Model',
config: {
hasMany: {model: 'Job', name: 'jobs'}
}
})
Ext.define('Job',{
extend: 'Ext.data.Model',
config: {
belongsTo: 'Crew'
}
})
Ext.create('Ext.data.Store', {
model: 'Crew',
storeId: 'crewStore',
grouper: {
grouperFn: function(record){
return record.get('name');
}
}
})
Ext.create('Ext.list',{
store: 'crewStore',
grouped: true,
})

This loads correctly, but the List will be a list of crews, not jobs. Is the best idea to flatten the data out? That seems to be the most common solution. You can use a custom reader for crewStore, but that defeats the purpose of having associations.

Code:



Ext.define('MyReader',{
extend: 'Ext.data.reader.Json',
getResponseData: function(response){
var data = this.callParent([response]);
var newData = [];
for(var i in data){
var crew = data[i];
for(var j in data[i].jobs){
var job = data[i].jobs[j]
job.crew_id = crew.id
job.crew_name = crew.name
newData.push(job)
}
}
return newData;
}
}

Is this the only realistic way to do this? I was thinking about making a Jobs store, and have the Crew store load it with data (a master/slave store), but that kills the association, right?


Aucun commentaire:

Enregistrer un commentaire