gpt4 book ai didi

javascript - 如何更新 knockoutjs 中的可观察数组元素?

转载 作者:可可西里 更新时间:2023-11-01 02:51:43 33 4
gpt4 key购买 nike

我有以下 JavaScript 数组,

[{"unitPrice": 2499,"currency":"$","productId":1,"retailerId":1,"productName":"XX ","formattedPrice":"$ 2,499","productImage":"Images/2012_08_12_00_45_39_4539.jpg","productQuantity":"9","totalPrice":19992},
{"unitPrice": 4999,"currency":"$","productId":2,"retailerId":1,"productName":"XX","formattedPrice":"$ 4,999","productImage":"Images/2012_08_12_00_46_45_4645.jpg","productQuantity":2,"totalPrice":9998},
{"unitPrice":4555,"currency":"$","productId":1,"retailerId":1,"productName":"XXXXX","formattedPrice":"$ 4,555","productImage":"Images/2013_02_12_10_57_49_5749_9868.png","productQuantity":3,"totalPrice":13665}]

这是相关的html,

<table>
<tbody data-bind="foreach: $root">
<tr>
<td><img width="45" height="45" alt="" data-bind="attr:{src: productImage}"/></td>
<td><span data-bind="html: productName"></span></td>
<td><span data-bind="html: formattedPrice"></span></td>
<td><input type="number" class="quantity" data-bind="value: productQuantity, attr:{'data-id': productId }" /></td>
<td><span data-bind="html: totalPrice"></span></td>
</tr>
</tbody>
</table>

然后我创建了可观察数组,

observableItems = ko.observableArray(items);
ko.applyBindings(observableItems);

现在我可以使用

       var obj = ko.utils.arrayFirst(list(), function (item) {
return item.productId === id;
});

但是当我改变时,

item.productQuantity = 20;

但是 UI 没有更新。也试过了,

item.productQuantity(item.productQuantity)

但是得到错误 productQuantity 不是一个函数

最佳答案

上述行为是因为只有数组是可观察的,而不是数组中的各个元素或每个元素的属性。

当您执行 item.productQuantity = 20; 时,这将更新该属性,但由于它不是可观察的,因此 UI 不会更新。

同样,item.productQuantity(20) 给您一个错误,因为 productQuantity 不是可观察的。

您应该着眼于为数组的每个元素定义对象结构,然后将该类型的元素添加到您的可观察数组中。完成此操作后,您将能够执行类似 item.productQuantity(20) 的操作,UI 将立即自行更新。

编辑 添加了 OP 提供的功能 :)。此函数会将数组中元素的每个属性转换为可观察对象。

function convertToObservable(list) 
{
var newList = [];
$.each(list, function (i, obj) {
var newObj = {};
Object.keys(obj).forEach(function (key) {
newObj[key] = ko.observable(obj[key]);
});
newList.push(newObj);
});
return newList;
}

结束编辑

如果您无法更改那段代码,您也可以执行类似observableItems.valueHasMutated() 的操作。但是,这不是一件好事,因为它会向 KO 和您的 UI 发出信号,表明整个数组已更改,并且 UI 将根据绑定(bind)呈现整个数组。

关于javascript - 如何更新 knockoutjs 中的可观察数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953248/

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