首页 > 解决方案 > Aurelia 绑定到带参数的函数并强制更新

问题描述

我已将 isSelected(item) 函数绑定到我的按钮,该函数将切换类以显示它是否被选中,但是此函数不会在更改时更新。

我不能使用计算属性,因为它需要一个参数。

有什么方法可以使用绑定函数使其工作,并使用 @computedFrom 装饰器等进行理想更新?

这里的例子:

https://codesandbox.io/s/aurelia-typescript-sandbox-8oksr?fontsize=14

您会注意到通过该函数正确绑定了人 2,但单击其他​​项目不会更新 UI。

-

这样做的原因

我想这样做的原因是一个有点复杂的源数组的结果。而不是我在这里作为示例给出的 people 数组。我的真实域更接近于包含项目的框列表,这些框可以包含其他框(可能无限),可以在任何级别选择项目。

标签: functionbindingaurelia

解决方案


更新 2

所以我在 github 上遇到了这个问题。其中一个答案表明,将观察到的项目传递给方法会自动使方法可观察。目前,您只是传递personisSelected(). 但是,人并没有被改变。我认为你可以通过改变你的方法来完成你正在寻找的isSelected()东西(注意在按钮的类绑定中对 isSelected 的调用发生了变化):

vm.ts

public isSelected(person, length){
   return this.selections.find(item => item.name === person.name);
}

视图.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,只能与未参数化的吸气剂一起使用。

@computedFrom('firstName', 'lastName')
get fullName() { return `${firstName} ${lastName}`}

所以我们想要做的问题是我们需要将索引或项目传递给我们的方法——这破坏了我们使用@computedFrom.

我不太喜欢的另一种选择......但它确实有效,是为您的每个 person 对象添加一个isSelected属性。然后您的代码将如下所示:

vm.ts

selectPerson(person){
    person.isSelected = !person.isSelected;  //De-selects if already selected
}

视图.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);
}

视图.html

<div repeat.for = "person of selections">
   ${person.name}
</div>

此处示例:https ://codesandbox.io/s/aurelia-typescript-sandbox-u92nk?fontsize=14


推荐阅读