15

我正在使用 ember.js-pre3 ember-data 修订版 11 构建项目管理应用程序。

如何初始化几个控制器并使它们在全球范围内可用。例如,我有一个 currentUser 控制器和 usersController,我需要在每个状态下访问它们。我曾经在 Ember.ready 函数中有以下代码,但它不再有效。我想我这样做的方式是为了调试。https://github.com/emberjs/ember.js/issues/1646

旧方式:

window.Fp = Ember.Application.create
  ready: () ->

  # Initialize Global collections
  appController = @get 'router.applicationController'
  store = @get 'router.store'

  # User controller sets usersController binding on applicationController
  # fetches all team users from server
  # json returned from server includes flag "isCurrent"
  usersController = @get 'router.usersController'
  usersController.set 'content', store.findAll(Fp.User) 
  appController.set 'usersController', usersController

  # CurrentUserController
  # sets currentUserController binding on applicationController
  # finds currentUser from usersController 
  currentUserController = @get 'router.currentUserController'
  currentUserController.set 'content', usersController.get('findCurrentUser')
  appController.set 'currentUserController', currentUserController

  @_super()

在所有应用程序状态下访问 currentUser 控制器的正确方法是什么。

4

1 回答 1

30

在最新版本的 ember (ember-1.0.0-pre.3.js) 中,您可以通过声明控制器依赖项来做到这一点。一旦声明了依赖项,就可以通过controllers属性访问它。例如:

window.App = Ember.Application.create();
App.ApplicationController = Ember.Controller.extend({   
  needs: ['currentUser', 'users']
});
App.CurrentUserController = Ember.ObjectController.extend({
  content: 'mike'
});
App.UsersController = Ember.ArrayController.extend({
  content: ['mike', 'jen', 'sophia']
});

由于 ApplicationController 需要 currentUser 和 users,这些控制器可以通过它的controllers属性访问,并且可以在应用程序模板中使用:

<script type="text/x-handlebars">
  <p>Signed in as {{controllers.currentUser.content}}</p>
  <h2>All Users:</h2>
  <ul>
    {{#each user in controllers.users}}
    <li> {{user}} </li>
    {{/each}}
  </ul>
</script>

这是一个工作示例:http: //jsfiddle.net/mgrassotti/mPYEX/

有关一些示例,请参见https://github.com/emberjs/ember.js/blob/master/packages/ember-application/tests/system/controller_test.js

于 2013-01-17T21:52:11.083 回答