2013-01-17 14 views
15

buduję aplikację do zarządzania projektami za pomocą rewizji ember.js-PRE3 Ember-data 11.Dostęp do kontrolerów z innych kontrolerów

Jak mogę zainicjować kilka kontrolerów i udostępniają je na całym świecie. Na przykład mam kontroler currentUser i usersController, do których potrzebuję dostępu w każdym stanie. Kiedyś miałem następujący kod w funkcji Ember.ready, ale już nie działa. Podejrzewam, że sposób, w jaki to robiłem, był przeznaczony do debugowania. https://github.com/emberjs/ember.js/issues/1646

stary sposób:

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() 

Co to jest właściwy sposób, aby mieć dostęp do kontrolera CurrentUser we wszystkich stanach aplikacyjnych.

Odpowiedz

30

W najnowszej wersji ember (ember-1.0.0-pre.3.js) można to zrobić, deklarując zależności kontrolera. Po zadeklarowaniu zależności będzie ona dostępna za pośrednictwem właściwości controllers. Na przykład:

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'] 
}); 

Od ApplicationController potrzebuje CurrentUser i użytkowników, te sterowniki są dostępne poprzez to controllers własność i może być używany z poziomu szablonu aplikacji:

<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> 

Oto przykład praca: http://jsfiddle.net/mgrassotti/mPYEX/

Zobacz https://github.com/emberjs/ember.js/blob/master/packages/ember-application/tests/system/controller_test.js dla niektórych przykładów:

Powiązane problemy