2
votes

Being that knockout observable arrays only update on changing an element in the array if that element is itself an observable, I am trying to "push" an element into an observable array but make it observable. I have tried the following statements, but both result in having an undefined value in my observable array:

viewModel.myObservableArray.push(ko.observable());

and

viewModel.myObservableArray.push(new ko.observable());

what would be the correct way to this?

2
that is not true. An observable array updates when elements in the observable array are added or removed (the elements themselves need not be observables). if you want to push an observable then you need to do viewModel.myOBservableArray.push(ko.observable('some value')) if it is string or viewModel.MyObservableArray.push(ko.observable({id: 1, name: 'something'})) - Sujesh Arukil

2 Answers

2
votes

Make what you are trying to put in the model an object like this

function MyObject(initValuye){
var self = this;
    var value = ko.observable(initValuye);
}

In your model

viewModel.myObservableArray.push(new MyObject(someValue));
0
votes

You can try like this also

viewModel.myObservableArray.push(ko.observable("Test"));

viewModel.myObservableArray.push(new ko.observable("Test"));