英文原文:http://emberjs.com/guides/controllers/dependencies-between-controllers/

管理控制器间的依赖(Managing Dependencies Between Controllers)

Sometimes, especially when nesting resources, we find ourselves needing to have some kind of connection between two controllers. Let’s take this router as an example:

有时候,特别是在嵌套资源时,可能需要为两个控制器建立某种联系。以下面的路由为例:

  1. App.Router.map(function() {
  2. this.resource("post", { path: "/posts/:post_id" }, function() {
  3. this.resource("comments", { path: "/comments" });
  4. });
  5. });

If we visit a /posts/1/comments URL, our Post model will get loaded into a PostController‘s model, which means it is not directly accessible in the CommentsController. We might however want to display some information about it in the comments template.

如果访问/posts/1/comments这个URL,Post模型会被设置为PostController的模型,其不可以在CommentsController中直接引用。然而又需要在comments模板中显示一些与其相关的信息。

To be able to do this we define our CommentsController to need the PostController which has our desired Post model.

为了实现这个功能,可以在CommentsController中声明其需要一个代表Post模型的PostController

  1. App.CommentsController = Ember.ArrayController.extend({
  2. needs: "post"
  3. });

This tells Ember that our CommentsController should be able to access its parent PostController, which can be done via controllers.post (either in the template or in the controller itself).

这里告诉EmberCommentsController应该能通过controllers.post来访问其父控制器PostController。(在模板和控制器中均可访问)。

  1. <h1>Comments for {{controllers.post.title}}</h1>
  2. <ul>
  3. {{#each comments}}
  4. <li>{{text}}</li>
  5. {{/each}}
  6. </ul>

We can also create an aliased property to give ourselves a shorter way to access the PostController (since it is an ObjectController, we don’t need or want the Post instance directly).

通过创建一个别名属性,可以提供一种更为简便的方式来访问PostController(因为PostController是一个ObjectController,这里并不直接需要一个Post实例)。

  1. App.CommentsController = Ember.ArrayController.extend({
  2. needs: "post",
  3. post: Ember.computed.alias("controllers.post")
  4. });

If you want to connect multiple controllers together, you can specify an array of controller names:

如果希望连接多个控制器,那么可以使用数组来指定控制器的名称:

  1. App.AnotherController = Ember.Controller.extend({
  2. needs: ['post', 'comments']
  3. });

For more information about aliased property, see the API docs for aliased properties.

更多关于别名属性的信息,请查看aliased properties API。