[英]How do I use a property path passed to an Ember Component?
我想做這樣的事情
App.FooComponent = Ember.Component.extend({
tagName: 'ul',
propertyPath: '',
data: []
});
在foo-component.hbs中(這顯然不起作用):
{{#each item in data}}
<li>{{propertyPath}}</li>
{{/each}}
我將使用以下組件:
{{foo-component data=content propertyPath='name'}}
內容是對象的集合,每個對象都有一個“名稱”屬性。
我嘗試通過使用計算屬性並將其綁定到組件中來完成此操作:
itemNames: function() {
var propertyPath = 'data.@each.' + this.get('propertyPath');
return this.get(propertyPath);
}.property(???)
但這有一個問題,即如何設置從屬密鑰,以便重新計算屬性。
我會用這樣的東西:
items: Ember.computed.map('data', function(dataObject) {
return {
name: dataObject.name,
otherProp: dataObject.otherProp
};
}).property('data.@each.{name, otherProp}')
您聲明一個計算屬性,該屬性將data
的對象映射到其他一些對象。 在您的函數中,您可以僅返回具有所需屬性的對象(我使用name
和otherProp
)。 然后,為確保該屬性otherProp
每個對象的name
和otherProp
屬性,我使用.property()
調用覆蓋了相關鍵。 (默認情況下, Ember.computed.map
將為您調用.property('data.@each')
。)
然后,在您的模板中:
{{#each items}}
<li>{{name}}</li>
{{/each}}
編輯:
動態屬性名稱有點奇怪。 一種方法是在創建時在類上聲明一個計算屬性。
init: function() {
var propertyPath = this.get('propertyPath');
this.reopen({
propertyPathUpdater: function() {
this.notifyPropertyChange('data');
}.observes('data.@each.' + propertyPath)
});
}
根據您的價值觀的更新方式,您可能需要對其進行一些修改,但希望您能理解。 想法是Ember不喜歡動態屬性。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.