4

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 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I'd wondered if I'd have to do that, just didn't feel right. Thanks for the fix, and for letting me know that it's a known issue.
It appears that the issue mentioned was addressed in knockout 3.0.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.