Knockout.js using `value:` binding in a `foreach` over a list of strings - does not update

前端 未结 2 834
小蘑菇
小蘑菇 2021-02-14 00:03

Here is a jsFiddle demonstrating the following problem:

Given a foreach binding over a list of (observable) strings, the observables do not seem to update from changes t

相关标签:
2条回答
  • 2021-02-14 00:20

    Every data object used in the default knockout bindings will always be unwrapped. So you are essentially binding to the value of the items in the list, not the observable as you are expecting.

    Observables should be properties of an object, not a replacement of the object itself. Set the observables as a property of some object so this doesn't happen.

    ​var vm = {
        list: [
            { value: ko.observable('123') },
            { value: ko.observable('456') }
        ]
    };
    
    <ul data-bind='foreach: list'>
        <li><input data-bind='value: value'/></li>
    </ul>
    
    <ul data-bind='foreach: list'>
        <li><span data-bind='text: value'></span></li>
    </ul>
    
    0 讨论(0)
  • 2021-02-14 00:37

    I worked around this by using value: $parent.list[$index()], as seen in this jsFiddle. The new bindings looks like this:

    <ul data-bind='foreach: list'>
        <li>
            <input data-bind='value: $parent.list[$index()]' />
        </li>
    </ul>
    

    One could perhaps improve on this with a custom binding.

    See also this related GitHub issue #708 for Knockout.js.

    Update for Knockout 3.0:

    Knockout now provides $rawData:

    <ul data-bind='foreach: list'>
        <li><input data-bind='value: $rawData'/></li>
    </ul>
    

    creates a two-way binding as expected.

    From the Binding Context documentation:

    $rawData

    This is the raw view model value in the current context. Usually this will be the same as $data, but if the view model provided to Knockout is wrapped in an observable, $data will be the unwrapped view model, and $rawData will be the observable itself.

    0 讨论(0)
提交回复
热议问题