gpt4 book ai didi

javascript - Aurelia class.bind 与 checked.bind 问题

转载 作者:行者123 更新时间:2023-11-30 09:51:39 26 4
gpt4 key购买 nike

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

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

<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>

然而,这并没有像预期的那样工作,这可以在 this plunk 中看到.

作为一种解决方法,我使用了一个 getter@computedFrom('selectedItems', 'items') 和/或 declarePropertyDependencies(App, 'classes', ['selectedItems', 'items']); ,如下:

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']);

但是,这也行不通,正如我们在 workaround plunk 中看到的那样.

它只有在没有使用 @computedFrom 和/或 declarePropertyDependencies 时才有效,而且这显然涉及脏检查。

有没有一种干净的方法来做到这一点?

最佳答案

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

这是一个例子: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=[];
}
}

关于javascript - Aurelia class.bind 与 checked.bind 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com