JS knockout - binding to an array of observable ints

I am trying to associate a simple array of integers with an unordered list with inputs, for example:

ViewModel

self.amounts = ko.observableArray(); for (var i=0; i<5; i++){ self.amounts.push(ko.observable(i)); } 

HTML

 <ul data-bind="foreach: amounts"> <li><input type="text" data-bind="value: $data"/></li> </ul> 

This creates a list with correctly entered inputs with numbers 0-4. However, when I change the value of any of the inputs, the ViewModel does not receive new values.

If I use an array of simple objects as an observable array, for example:

 [{amt: 0}, {amt: 1}, {amt: 2}] 

and configure the HTML to bind the input to the "amt" property, and then changing the values ​​on the inputs leads to changes in the ViewModel.

Is it possible to use an array of simple values ​​and achieve two-way binding without using a workaround that modifies the original data model? If so, what am I doing wrong?

edit: this question is different from the one on which it was marked as a duplicate of Knockout JS - How to properly bind the observed array ..., this is about a special case of two-way binding for simple elements such as ints or strings.

+4
source share
2 answers

This seems to be a recurring question, and my hunch was correct. $ data will always expand observable data, so instead you should use an array of names and value pairs.

See this question: JS Knockout - How to properly bind an observable array

+3
source
In this case, the data

$ will not work. Instead, you can create an array of such objects:

 <ul data-bind="foreach: amounts"> <li> <input type="text" data-bind="value: value" /> </li> </ul> <button data-bind="click: checkValues">Check</button> 

. .

 var MyNumber = function (name, value) { this.name = ko.observable(name); this.value = ko.observable(value); }; var VM = function () { this.amounts = ko.observableArray(); this.checkValues = function () { for (var i = 0; i < 5; i++) { console.log('amount = ' + vm.amounts()[i].value()); } }; }; var vm = new VM(); vm.amounts().push(new MyNumber('a', 1)); vm.amounts().push(new MyNumber('b', 2)); vm.amounts().push(new MyNumber('c', 3)); vm.amounts().push(new MyNumber('d', 4)); vm.amounts().push(new MyNumber('e', 5)); ko.applyBindings(vm); 
+1
source

All Articles