Доступ к контроллерам с других контроллеров
Я создаю приложение для управления проектами, используя версию 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 во всех состояниях приложения.
Ответы
Ответ 1
В последней версии 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 для некоторых примеров