Sisir Sisir -4 years ago 151
Javascript Question

EmberJS - How to Globally set an property of all component?

I have a piece of data (object) that is printed as a global variable from server side script.

user = { id : 1, name: 'foo', avatar : 'http://foo.com/avatar.jpg'}


This piece of information is requires in various part of the whole application including some components.

I know I can go through each component controller and set a property to save the user object.

App.FooBarComponent = Ember.Component.extend({
user: user
});


App.AnotherFooComponent = Ember.Component.extend({
user: user
});


How do I reduce this repetition? Is there a way I can set the property for all the components so the variable is available to handlebars expression?

<script type="text/x-handlebars" id="components/foo-bar">
<h1>{{user.name}}</h1>
</script>

<script type="text/x-handlebars" id="components/another-foo">
<h1>{{user.name}}</h1>
</script>


I was under the impression that I should be able to access any global js variables from handlebar expression. But I seems isn't the case.

Answer Source

You can use your application controller for this purpose :)

 <h1>{{controllers.application.user.name}}</h>

However you will need your ApplicationController in the controllers :)

Another way is to make a custom Component qand then extend it like

 App.MyComponent = Ember.Component.extend({
      user : user
 });
 AppFooComponent = App.MyComponent.extend({
     //user is gotten from MyComponent
 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download