Aurelia类的问题.使用checked.bind绑定

Issue with Aurelia class.bind with checked.bind

本文关键字:checked bind 绑定 使用 问题 Aurelia      更新时间:2023-09-26

我正试图以一种依赖于checked.bind的方式使用class.bind

我的用例非常简单。我有一个项目列表,使用table显示。该表的每一行都有一个checkbox。每当选中(该行的)相应的checkbox时,我想将该行标记为"已选择"。为此,我使用了以下绑定:

<table class="table table-striped table-hover table-responsive">
    <tbody>
      <tr repeat.for="item of items" class.bind="$parent.selectedItems.indexOf(item)>-1?'info':''">
        <td>
          <input type="checkbox" checked.bind="$parent.selectedItems" model.bind="item" />
        </td>
        <td>${item.id}</td>
        <td>${item.name}</td>
      </tr>
    </tbody>
</table>

然而,同样的方法并没有按预期发挥作用,这可以从这个plunk中看出。

作为一种变通方法,我使用了带有@computedFrom('selectedItems', 'items')和/或declarePropertyDependencies(App, 'classes', ['selectedItems', 'items']);getter,如下所示:

import {computedFrom, declarePropertyDependencies} from "aurelia-framework";
export class App {
   ...
    @computedFrom('selectedItems', 'items')
    get classes() {
        const self = this;
        const retval= self.items.map((item: any) => {
            return self.selectedItems.indexOf(item) > -1 ? "info" : "";
        });
        return retval;
    }
}
//declarePropertyDependencies(App, 'classes', ['selectedItems', 'items']);  

然而,这也不起作用,正如在这个变通方法中可以看到的那样。

只有在不使用@computedFrom和/或declarePropertyDependencies的情况下,它才有效,而且这显然涉及脏检查。

有干净的方法吗?

只要表达式中使用的属性发生更改,绑定系统就会重新评估类绑定表达式class.bind="$parent.selectedItems.indexOf(item)>-1?'info':''"selectedItems属性永远不会更改,它仍然是同一个数组实例。可以理解,这有点令人困惑,因为数组实例正在发生变化。这里有一个可以使用的解决方法:将selectedItems.length添加到绑定表达式中。。。我们知道当从数组中推送/弹出项目时,它会发生变化。

以下是一个示例:https://gist.run?id=09d32941842352ff0025

app.html

<template>
  <p>${message}</p>
  <table class="table table-striped table-hover table-responsive">
    <tbody>
      <tr repeat.for="item of items" class.bind="selectedItems.length === 0 || selectedItems.indexOf(item) === -1 ? '' : 'info'">
        <td>
          <input type="checkbox" checked.bind="selectedItems" model.bind="item" />
        </td>
        <td>${item.id}</td>
        <td>${item.name}</td>
      </tr>
    </tbody>
  </table>
  ${selectedItems.length} items selected
</template>

app.js

export class App {
  constructor(router) {
    this.message = "Hello World!";
    this.items = [{
      id: 1,
      name: "A"
    }, {
      id: 2,
      name: "B"
    }, {
      id: 3,
      name: "C"
    }];
    this.selectedItems=[];
  }
}