我刚刚开始学习 Ember,有一件事让我感到困惑,即我是否可以在模板中访问组件的方法。
例如,我有一个 note-list
组件,它呈现 note-line
列表如下:
<ul class="list">
{{#each notes as |note|}}
{{note-line note=note index=@index selected=(isSelected note)}}
{{/each}}
</ul>
note-list
组件定义为:
Ember.Component.extend({
tagName: '',
isSelected(note) {
return note.id === this.get('selectedNote').id
}
})
但我收到错误Assertion Failed: A helper named 'isSelected' could not be found
。
我想我可以用助手来解决它,但是为特定组件的行为创建一个单独的助手似乎不是一个好的解决方案。
请帮助建议我一些更好的方法来处理它。
非常感谢。
最佳答案
在您的情况下,您的组件可以确定自己是否被选中。实际上,您有一个函数 isSelected
,无论注释行是否被选中,它都会返回一个 bool 值。
您必须考虑使用计算属性来实现此目的。
note-line
组件定义如下:
Ember.Component.extend({
tagName: '',
note: null,
isSelected: Ember.computed('note', function() {
return this.get('note.id') === this.get('selectedNote.id')
})
})
然后,在您的组件模板中,isSelected
可作为一个简单的组件变量使用,并在 note
更新时更新。
最后,您可以像这样简单地使用您的组件:
<ul class="list">
{{#each notes as |note|}}
{{note-line note=note index=@index}}
{{/each}}
</ul>
但在这种情况下,正如您在评论中指出的那样,您需要将 selectedNote
传递给每个组件,以便它们更新 isSelected
属性。
实现此目的的一种方法是在模型本身中拥有一个 isSelected 属性,如记录 here .在 route
内的 model
函数中,您只需像这样设置此属性:
model: function() {
return this.store.find('notes')
.then(function(notes) {
notes.forEach(function(note) {
note.set('isSelected') = true || false; // here will be implemented your function to determine if note is selected or not
});
return notes;
})
})
}
然后在您的组件模板中,isSelected
与任何其他属性一样在 note
中可用。
关于javascript - 在模板中使用 Ember 组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32219607/