I\'m writing an app with EmberJS v1.0.pre. I have an ArrayController
which contains a list of all persons. There are a bunch of nested views showing the person, the
"From the pure MVC standpoint it feels like there should be a controller for each child"
You don't need a controller for each item, but instead an ArrayController for each collection of objects (People, Pets, Notes). By the way, any actions on child objects (dogs, notes) shouldn't be passed to App.PersonsController
. That would break the Separation of Concerns principle.
Ember.Router docs cover the case where you want to nest views in a single object ( e.g. /:people_id
). But you want to nest views for an array of objects. I can't think of a way to nest {{outlet}}
views, but you can do the following:
Load the objects People, Pets, Notes in 3 ArrayControllers, and delegate actions on child objects to its corresponding ArrayController.
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
route: '/',
persons: Ember.Route.extend({
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('persons');
// App.Note.find() fetches all Notes,
// If you are not using ember-data, make sure the notes are loaded into notesController
router.set('notesController.content', App.Note.find());
router.set('petsController.content', App.Pet.find());
}
})
})
});
And then your people
template should look like:
{{#each person in people}}
My name is {{person.name}}
{{#each pet in person.pets}}
I have a pet with name {{pet.name}}
Delete pet
{{/each}}
{{view Ember.TextField valueBinding="myNewPetName" type="text"}}
Add a new pet for this person
{{#each note in person.notes}}
{{/each}}
As you can see, the actions on child objects are delegated to its controller (pet -> petsController), passing the object as the context. In the case of the create
action, the controller needs to know to which person the pet belongsTo
. Therefore we pass 2 contexts: the person, and the properties of the pet (for simplicity I assumed just a name for the pet).
In your App.petsControllers you should have actions along the lines:
App.PetsController = Ember.ArrayController.extend({
delete: function(e) {
var context = e.context;
this.get('content').removeObject(context);
// Also, if you use ember-data,
// App.Pet.deleteRecord(context);
},
create: function(e) {
var petName = e.contexts[0]
var person = e.contexts[1];
this.get('content').pushObject({name: petName, person: person});
// with ember-data:
// App.Pet.createRecord({name: petName, person: person});
}
});