Knockout 绑定不会使用简单的 observables 数组更新 [英] Knockout binding doesn't update using array of simple observables
问题描述
我的视图模型中有一个字符串列表.要编辑它们,我希望每个都显示为带有文本框的 和一个
以删除项目.所以,对于列表
['A', 'B']
,我想要这样的东西:
I have a list of strings in my view model. To edit them, I want each to appear as an <li>
with a textbox, and a <button>
to remove the item. So, for the list ['A', 'B']
, I want something like this:
<ul data-bind="foreach: titles">
<li>
<input value="A" data-bind="value:$data" />
<button data-bind="click: $root.remove">remove</button>
</li>
<li>
<input value="B" data-bind="value:$data" />
<button data-bind="click: $root.remove">remove</button>
</li>
</ul>
<button data-bind="click: add">add</button>
我最初可以创建它,但没有更新要反映在视图模型中的值,并且无法使删除按钮工作.
I can create that initially, but am not getting updates to the values to reflect in the view model, and can't get the remove buttons working.
我最初有一个 observableArray
纯字符串,然后更新为 observable
字符串的 observableArray
.使用普通字符串,删除按钮可以工作,但可以预见的是,它没有更新视图模型.
I initially had an observableArray
of plain strings, then updated to an observableArray
of observable
strings. With the plain strings, the remove button worked, but it, predictably, didn't update the view model.
我已经设置了一个 JS 小提琴,这个问题相当孤立:http://jsfiddle.net/bdukes/uvyH3/2/
如果有一种既定的或更好的方法可以做到这一点,我很想知道.
If there's an established or better way of doing this, I'd love to know.
此外,作为一个不相关(且不太重要)的问题,stringifyJson
实用程序似乎总是为数组中的每个项目提供空结果.
Also, as an unrelated (and less important) issue, the stringifyJson
utility always seems to give me empty results for each item in the array.
推荐答案
Knockout 当前不适用于纯 observable 数组(问题已记录 此处).
Knockout does not currently work well with an array of pure observables (issue logged here).
为了使其正常工作,您需要您的项目是包含可观察对象的对象,例如:
To make this work properly, you need your items to be objects that hold observables like:
{ val: ko.observable("something") }
这是您的小提琴更新以使用这些类型的对象:http://jsfiddle.net/rniemeyer/GgFa9/
Here is your fiddle updated to use these type of objects: http://jsfiddle.net/rniemeyer/GgFa9/
这篇关于Knockout 绑定不会使用简单的 observables 数组更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!