首页 > 解决方案 > 剔除选择值到 $data

问题描述

我有两个可观察的数组,它们都包含相同模型类型的对象:

数组 1 和数组 2

我有以下代码

<!-- ko foreach: array2 -->

<select data-bind="options: $parent.array1(), optionsText: 'DisplayName', value: $data }">
</select>
<!-- /ko -->

局部视图模型

array1 = ko.observablearray([])
//I then grab objects from a database and push them to this array1

array2 = ko.observalbearray([])
//now I loop through array1 and based on some conditions, add the matching objects to array2. So in essense, array2 is a subset of array1

//I also have some logic here where I have a computed observable that gets computed based on the array2, and hence it's important for me to detect changes to this array.

我在这里要做的是将 select 的“值”分配给来自 foreach 循环的 array2 中的当前项目。但是当我从下拉列表中更改值时,我希望在相应的 array2 中更改它,并注意 array2 中的更改。所以假设我们在下拉列表中有值'a'、'b'、'c'(所以这是array1),并且说array2是'b'、'c',现在从两个下拉列表中的第一个(因为array2 大小为 2),我将 'b' 替换为 'a'。我希望这种变化反映在 array2 中,并且我计算的可观察值被重新计算。

使用上面的代码,我可以设置值,但我没有注意到数组发生了变化。我不知道如何使这项工作。有什么建议么?

我还应该添加 array1 和 array2 中的元素不是 obervables)

标签: knockout.js

解决方案


推荐阅读