我有以下的JavaScript阵列,如何更新knockoutjs中的可观察数组元素?
[{"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)
但是,得到误差产品数量不是一个函数
observableItems.valueHasMutated()不起作用 – user960567 2013-02-19 08:55:34
通过添加此功能获得它, function conve rtToObservable(list){var_new_list = [];}} $。每个(列表,函数(i,obj))var newObj = {}; Object.keys(obj).forEach(function(key){newObj [key] = ko.observable(obj [key]); }); newList.push(newObj); }); return newList; } – user960567 2013-02-19 09:19:09
请把这个里面的答案。 – user960567 2013-02-19 09:19:35