imgen
imgen

Reputation: 3133

Knockoutjs: the $data in foreach binding is not updating underlying element

I have below js code

$(document).ready(function () {
    var viewModel = {
        predefinedGrades: [
            ko.observable("Excellent"),
            ko.observable("Good"),
            ko.observable("OK"),
            ko.observable("Average"),
            ko.observable("Bad")],
        observable: ko.observable("good")
    };
    ko.applyBindings(viewModel);
});

Below is my view

<div data-bind="foreach: predefinedGrades">
    <input type="text" data-bind="value: $data, valueUpdate: 'keyup'"/>
</div>

<input type="text" data-bind="value: observable, valueUpdate: 'keyup'"/>

The problem is that when I update the text in the input of foreach binding, the underlying array won't change. But if I change the text with the last text input of the binding observable, the observable field can change after keyup event. How so? What am I missing?

Upvotes: 0

Views: 223

Answers (1)

Russ Cam
Russ Cam

Reputation: 125488

If you use $rawData instead of $data in your foreach binding, it will work as expected.

From the docs

$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.

Upvotes: 1

Related Questions