【问题标题】:Aurelia force dirty checking without getterAurelia 在没有 getter 的情况下强制进行脏检查
【发布时间】:2017-12-28 10:27:52
【问题描述】:

我正在尝试根据函数调用的结果有条件地向元素添加一个类,但 Aurelia 不会在其参数更改时重新运行该函数。通常我会使用 getter 来强制进行脏检查,但因为我的函数需要不可能的参数。

有问题的函数如下所示:

isVisible (item, filters) {
    // If there are no filters selected, or at least one of the item's tag names are inside the filters the item is considered visible
    return (!filters.length || (filters.length && item.tags.some(tag => {
        return filters.indexOf(tag.name) !== -1 ? true : false;
    })));
}

如果不是很明显,它需要一个 item 和一个字符串数组 (filters),然后检查 item.tags[].name 是否在 filters 数组内。

在我看来是这样使用的:

<item repeat.for="item of items" item.bind="item" class="${isVisible(item, filters) ? 'show' : 'hide'}"></item>

我还尝试将代码直接添加到视图中,我认为这会强制 Aurelia 重新计算事物,但是当将函数的全部代码添加到视图中时(在 ${code here} 内),我收到意外的解析错误 @ 987654329@.

【问题讨论】:

标签: aurelia


【解决方案1】:

您上面的示例足以在filters 更改时对其进行重新评估。但是,如果您对filters 进行变异,Aurelia 将无法获取更改,因为出于性能原因,数组观察不是自动的。您可以通过使用 filters 的不可变实例来解决此问题,或者另外观察 filters 长度,如下所示:

<item repeat.for="item of items"
    item.bind="item"
    class="${isVisible(item, filters, filters.length) ? 'show' : 'hide'></item>

【讨论】:

  • 很好,只需传入filters.length 就可以了!我明白为什么,尽管它确实感觉有点像黑客......
  • 一个问题,实际上filters 数组实际上在我的VM 中是可用的,所以从我的角度传递它并不是绝对必要的。有什么方法可以在只传入item 时达到相同的结果; isVisible(item)?是否有装饰器或我可以在 VM 的 isVisible 方法上使用的东西?
  • 你好奇的是方法观察,目前不支持。我想你能做的最好的事情是使用一个信号,每次你改变filters,信号repeat绑定重新评估。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2015-04-07
  • 2020-06-28
  • 2015-10-04
  • 1970-01-01
  • 2017-06-11
相关资源
最近更新 更多