Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing controllers from other controllers

I am building a project management app using ember.js-pre3 ember-data revision 11.

How do I initialize a couple of controllers and make them available globally. For example I have a currentUser controller and usersController that I need access to in every state. I used to have the following code in the Ember.ready function but It no longer works. I guess the way I was doing it was intended for debugging. https://github.com/emberjs/ember.js/issues/1646

Old Way:

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

What is the proper way to have access to the currentUser controller in all application states.

like image 574
Aaron Renoir Avatar asked Jan 17 '13 21:01

Aaron Renoir


1 Answers

In the latest version of ember (ember-1.0.0-pre.3.js) you can do this by declaring controller dependencies. Once a dependency has been declared, it will be accessible via the controllers property. For example:

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

Since ApplicationController needs currentUser and users, those controllers are accessible via it's controllers property and can be used from within the application template:

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

Here's a working example: http://jsfiddle.net/mgrassotti/mPYEX/

See https://github.com/emberjs/ember.js/blob/master/packages/ember-application/tests/system/controller_test.js for some examples

like image 135
Mike Grassotti Avatar answered Nov 14 '22 06:11

Mike Grassotti