2015-01-06 41 views
0

我有一段從服務器端腳本打印爲全局變量的數據(對象)。EmberJS - 如何全局設置所有組件的屬性?

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

這條信息需要在整個應用程序的各個部分包括一些組件。

我知道我可以通過每個組件控制器並設置一個屬性來保存用戶對象。

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


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

如何減少這種重複?有沒有辦法可以設置所有組件的屬性,以便變量可用於車把表達式

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

我的印象是,我應該能夠從句柄表達式中訪問任何全局js變量。但我似乎並非如此。

回答

1

您可以使用您的應用程序控制器用於此目的:)

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

然而,你將在控制器needApplicationController :)

另一種方式是創建一個自定義組件qand然後擴展它像

App.MyComponent = Ember.Component.extend({ 
     user : user 
}); 
AppFooComponent = App.MyComponent.extend({ 
    //user is gotten from MyComponent 
}); 
+0

例'needs'可以在這裏找到http://stackoverflow.com/a/18386236/550907 – Sisir

1

使用Ember.Application.inject(http://emberjs.com/api/classes/Ember.Application.html#method_inject

var user = Ember.Object.create({ 
    id : 1, 
    name: 'foo', avatar : 'http://foo.com/avatar.jpg' 
}); 
App.register('user:main', user); 
App.inject('component', 'user', 'user:main'); 

然後在你的組件模板只是做了如何使用

{{user.name}} 
相關問題