Is there a way to share variables across controllers?


#1

How can I share variables across controllers? For example I would like to have a global “token” variable, or possibly a current_user variable that all routes can share.

Similarly I might want to save API URLs as constants for certain REST endpoints.

I guess environment variables may be used, or perhaps an object kept in the data store may retain session values for the lifetime of the application.

Any pointers or examples would be appreciated.

Thank you, Bahadir


#2

A few approaches come to mind.

  1. Define these variables in your application controller. If there are variables that are shared across the application this is a logical place to keep them.
  2. Define a common controller to hold these shared variables and then use the ‘needs’ hook to allow some controllers to include the common or shared controller. Similar to the application controller but more specific. See the guides for example of using needs. http://emberjs.com/guides/controllers/dependencies-between-controllers/
  3. Initialize and inject a “service” object into your app. This is a more advanced approach but would allow a more global and pervasive approach. For example ‘model’ and ‘store’ are examples of injected hooks that the ember framework inserts. You can do something similar. This is often called “dependency injection”. http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/

#3

Best, concise, and thorough answer (probably) possible.


#4

Thank you. The example you posted with “needs” was exactly what I needed.

Bahadir