2013-01-17 228 views
15

访问控制器我建立使用ember.js-PRE3烬数据的修订11.从其他控制器

项目管理应用程序如何初始化一对夫妇的控制器,并使其全局可用。例如,我有一个当前用户控制器和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控制器中的所有应用程序状态的正确方法。

回答

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和用户,这些控制器是可访问通过它的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某些示例