更新 2
所以我遇到了this issue on github。其中一个答案表明,将观察到的项目传递给方法会自动使方法可观察。目前,您只是将person 传递给isSelected()。但是,人并没有被改变。我认为您可以通过像这样更改您的 isSelected() 方法来完成您正在寻找的内容(注意在按钮的类绑定中对 isSelected 的调用发生了变化):
vm.ts
public isSelected(person, length){
return this.selections.find(item => item.name === person.name);
}
view.html
<button
class="btn-gradient mini ${isSelected(person, selections.length) ? 'green': 'red'}"
click.delegate="selectPerson(person)"
repeat.for="person of people">
${person.name}
</button>
示例:https://codesandbox.io/s/aurelia-typescript-sandbox-oelt7?fontsize=14
原帖
我在尝试实现isSelected() 方法来控制选定的指标类时遇到了同样的问题。我已经查看了@computedFrom。
我可能错了,但从我所见@computedFrom 只能与未参数化的 getter 一起使用。
@computedFrom('firstName', 'lastName')
get fullName() { return `${firstName} ${lastName}`}
所以我们想要做的问题是我们需要将索引或项目传递给我们的方法——这破坏了我们使用@computedFrom的能力。
另一种我不太喜欢...但它确实有效的替代方法是为您的每个 person 对象添加一个 isSelected 属性。然后您的代码将如下所示:
vm.ts
selectPerson(person){
person.isSelected = !person.isSelected; //De-selects if already selected
}
view.html
<button
class="btn-gradient mini ${person.isSelected ? 'green': 'red'}"
click.delegate="selectPerson(person)"
repeat.for="person of people">${person.name}</button>
(或者,正如我最近向我建议的那样,将您的 person 对象包装在一个包装类中)
public class SelectableWrapper {
constructor(public person : Person, public isSelected : boolean){}
}
更新 1
要解决显示所选项目列表的问题(以及“着色”所选项目),您可以执行以下操作(除了我已经显示的内容):
vm.ts
//Remove selections property and add it as a getter
get selections(){
return this.people.filter(p => p.isSelected);
}
view.html
<div repeat.for = "person of selections">
${person.name}
</div>
此处示例:https://codesandbox.io/s/aurelia-typescript-sandbox-u92nk?fontsize=14