在模板中使用Ember组件的方法

Vin*_*hBS 1 javascript ember.js

我刚开始学习Ember,有一件事我很困惑,如果我可以在模板中访问组件的方法.

例如,我有一个note-list组件,呈现如下列表note-line:

<ul class="list">
  {{#each notes as |note|}}
    {{note-line note=note index=@index selected=(isSelected note)}}
  {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

note-list组件定义为:

Ember.Component.extend({
    tagName: '',
    isSelected(note) {
        return note.id === this.get('selectedNote').id
    }
})
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误Assertion Failed: A helper named 'isSelected' could not be found.

我想我可以用帮助器解决它,但似乎不是一个很好的解决方案来为特定组件的行为创建一个单独的帮助器.

请帮忙告诉我一些更好的处理方法.

非常感谢.

dyn*_*ast 5

在您的情况下,您的组件可以确定自己是否被选中.实际上,您有一个isSelected返回布尔值的函数,无论是否选择了音符行.

您必须考虑使用计算属性来实现此目的.

note-line组件将被定义为:

Ember.Component.extend({
    tagName: '',
    note: null,
    isSelected: Ember.computed('note', function() {
        return this.get('note.id') === this.get('selectedNote.id')
    })
})
Run Code Online (Sandbox Code Playgroud)

然后,在组件模板中,isSelected可用作简单的组件变量,并在更新时note更新.

最后,您可以像这样简单地使用您的组件:

<ul class="list">
  {{#each notes as |note|}}
     {{note-line note=note index=@index}}
  {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,正如您在评论中指出的那样,您需要传递selectedNote给每个组件,以便他们更新isSelected属性.

这样做的一个方法是在模型本身作为一个记录IsSelected属性在这里.在你的model函数中route,你只需要像这样设置这个属性:

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;
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

然后在您的组件模板中,isSelected可以note像任何其他属性一样使用.

  • 我更清楚你想要什么.请看我更新的答案. (2认同)