Using Ember component's methods inside template

时光总嘲笑我的痴心妄想 提交于 2019-12-24 11:37:31

问题


I've just started learning Ember and one thing I'm confused that if I can access component's method inside the template.

For example, I have a note-list component that render list of note-line as follow:

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

The note-list component is defined as:

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

But I'm getting error Assertion Failed: A helper named 'isSelected' could not be found.

I think I could solve it with helpers, but it seems to be not a good solution to create a separate helper for a behaviour of a specific component.

Please help to advise me some better way to deal with it.

Thanks very much.


回答1:


In your case, your component can determine itself if it is selected or not. Indeed, you have a function isSelected that returns a boolean whether the note-line is selected or not.

You must consider using a computed property to achieve this.

The note-line component would be defined like :

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

Then, in your component template, isSelected is available as a simple component variable and is updated when note is updated.

Finally, you can simply use your component like this :

<ul class="list">
  {{#each notes as |note|}}
     {{note-line note=note index=@index}}
  {{/each}}
</ul>

But in this case, as you pointed out in your comment, you would need to pass selectedNote to each component in order for them to update the isSelected property.

One way to do this would be to have a isSelected property in the model itself as documented here. In your model function inside your route, you will just have to set this property like this :

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;
        })
    })
}

Then in your component template, isSelected is available in note like any other attribute.



来源:https://stackoverflow.com/questions/32219607/using-ember-components-methods-inside-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!