Knockout binding doesn't update using array of

2019-02-23 18:05发布

问题:

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.

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.

I've setup a JS fiddle with the issue fairly isolated: http://jsfiddle.net/bdukes/uvyH3/2/

If there's an established or better way of doing this, I'd love to know.

Also, as an unrelated (and less important) issue, the stringifyJson utility always seems to give me empty results for each item in the array.

回答1:

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") }

Here is your fiddle updated to use these type of objects: http://jsfiddle.net/rniemeyer/GgFa9/



标签: knockout.js