从其他控制器访问控制器

Aar*_*oir 15 ember.js ember-data

我正在使用ember.js-pre3 ember-data revision 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()
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*tti 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']
});
Run Code Online (Sandbox Code Playgroud)

由于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>
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子:http://jsfiddle.net/mgrassotti/mPYEX/

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