EmberJS Nested Views and Controllers
Asked Answered
H

4

10

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, their pets and the notes for each pet.

|----------------------------------------|
| John                                   | <- Person
|----------------------------------------|
|   Quincy (Dog)                         | <- Pet
|     - Super ornery                     | <- Note
|     - Likes XYZ Dog food               |
|     - Will eat your socks              |
|                                        |
|   Tom (Cat)                            |
|    - Always (not) catching mice        |
|                                        |
|----------------------------------------|
| Roger                                  |
|----------------------------------------|
|   V (Dog)                              |
|    - Likes XYZ Dog food                |
|    - Sneezes, but it's ok              |
|                                        |
|----------------------------------------|
| ...                                    |

From the pure MVC standpoint it feels like there should be a controller for each child, but I can't figure out how to achieve that in Ember. There is the top Array controller and then all the individual views. If I want to delete a note, or edit it, it seems like I need to pass the view's context up to the controller.

// in the view
click: function () {
  this.get('controller').updateNote(this.get('content'))
}

This feels really bad to me, the View is not supposed to be the authoritative source for data. My assumption is that an ArrayController would instantiate an itemControlerClass along with the itemViewClass.

UPDATE: I have created a fiddle to better illustrate my problem. The functionality is intentionally incomplete, the purpose is to finish the functionality by increasing the content when an item on the list is clicked.

UPDATE: Sorry, I deleted the fiddle on accident! I'm doing some work on a final solution, so I'll try to create a new fiddle w/ the solution.

Highoctane answered 26/9, 2012 at 13:5 Comment(4)
Go through this emberjs.com/guides/outletsHagan
There's no real firm information in that guide about my problem. I've read it before, and I'll keep referring to it, but haven't found anything yet.Highoctane
Check this out then #12595996Hagan
I read techiferous.com/2012/05/… and it was very helpful. But, still to no avail.Highoctane
B
12

"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}}
  <h1>My name is {{person.name}}</h1>

  {{#each pet in person.pets}}
     I have a pet with name {{pet.name}}
     <a {{action delete pet target="App.router.petsController">Delete pet</a>
  {{/each}}      

  {{view Ember.TextField valueBinding="myNewPetName" type="text"}}
  <a {{action create myNewPetName person target="controller"}}>
    Add a new pet for this person
  </a>


  {{#each note in person.notes}}
    <!-- delete, create, edit ... -->
  {{/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});
   }
});  
Byrnie answered 4/10, 2012 at 22:35 Comment(1)
This is easily the most complete example I've seen of my problem, thank you! I'm going to take this answer and run with it. There are a few issues I still need to address though. Passing context from the view is my original complaint to this problem, but it seems unavoidable. Also, the controllers cannot simply be set to all Notes, since they are a child of (literally embedded in) Pets, and same with Pets and People. To me, this doesn't feel like an architectural problem. I'll need to set the parent context first I suppose. I will update my question with anything more I discover. Thanks again.Highoctane
A
1

You should be using outlets. They are little 'placeholders' in Ember views that can be handled with different controllers.

There is a fair explanation on them on the link above, where you have already checked and found nothing. But before you get back to that, read this first: http://trek.github.com/

If any of these still doesn't help you, let know and I'll put together an axample for you.

Apomixis answered 29/9, 2012 at 8:44 Comment(2)
I've read both articles, even before my post. I am also using outlets, however, outlets do not delegate responsibility of the content to a separate controller. Thank you for your offer to put together an example, I'd love to see one. I will also whip something up in jsfiddle to better explain my problem.Highoctane
I've updated my question with a fiddle. Thanks for your continued help.Highoctane
S
1

I think this is what your are looking for, take a look, it is pretty straight forward, you can also check this example. Basically you can achieve what you want with outlets, routers and actions for connecting all your outlets.

Sausage answered 4/10, 2012 at 15:56 Comment(2)
I'll take another stab at it. This article, gist.github.com/3002177, has also been a great help. I think my problem has been using the ArrayController. When really it should just be a controller with outlets? Does that make sense?Highoctane
Any chance you can provide a different, more pertinent, example? The one you provided doesn't have any parallel to my question. Specifically, my problem isn't with routing, it's about delegation of control to nested resources. Outlets are interesting, but even with all the suggestions to use them, there is still no useful example of how they solve my problem.Highoctane
A
0

I'm new to Ember and have been looking for a way to do something similar. In the top-level ArrayController, I just used the itemController property and it worked great:

App.PeopleController = Ember.ArrayController.extend({
    itemController: "Person"
});

App.PersonController = Ember.ObjectController.extend //...

My complete solution is in this js fiddle. Unfortunately, the way I'm getting the PetController instances to work seems hacky to me.

Assistance answered 13/2, 2013 at 4:1 Comment(1)
The updates since v1.0pre have been super helpful and I've had much better luck. I'll dig further into what you did and see how it goes!Highoctane

© 2022 - 2024 — McMap. All rights reserved.