Knockout Data-Bind to Array Element Only Half-Work

2019-09-04 12:22发布

问题:

I am binding to an observable inside an array and the binding only seems to take affect when reading the value from the model for the first time. Subsequently making changes to the input bound to the observable does not update the model.

A JSFiddle is here: http://jsfiddle.net/coverbeck/hK49f/88/. Here's the HTML:

<div>
    <input data-bind="value: work"/>
    <span data-bind="text: work"></span>
</div>
<!-- ko foreach: nowork -->
<div>
    <input data-bind="value: $data"/>
    <span data-bind="text: $data"></span>
</div>
<!-- /ko -->

And the JavaScript:

var viewModel = {
    work: ko.observable('Change me and span changes'), 
    nowork : [ko.observable("Change me and span doesn't update")]
}
ko.applyBindings(viewModel);

When you type something in the first input, the span that is bound to the observable updates. When you type something in the second input, that span that is bound to the observable inside an array does not update. But that input and span start out correctly.

Making "nowork" a ko.observableArray instead of a plain array makes no difference (nor would I expect it to).

I feel like I'm missing something obvious, but I don't see what. Does anybody have an idea what is going on?

Thanks,

Charles

回答1:

The issue is the foreach binding, in foreach binding you bind the input with $data and $data property is not an observable its an unwrapped observable (only content of an observable). So thats why change to input field is not changing your observable property value.

You should bind the input with observable. Here's a working fiddle

http://jsfiddle.net/w7WQh/



标签: knockout.js