Reputation: 810
I have an observable array of observables as follows
appViewModel.rollArray = ko.observableArray([{
diceAmount: ko.numericObservable(1),
diceType: ko.observable(null),
diceAddition: ko.numericObservable(0),
diceMultiplication: ko.numericObservable(1)
}]);
There are bindings that are watching for these properties as well such as the following
<input type="number" data-bind="value: rollArray()[rollIndex()].diceAmount" />
This array gets populated and changed quite a bit in the web application, but I am in need of having a "reset" button. Which will restore the appViewModel.rollArray to its default state (as I defined above). The problem is that if I simply re-define rollArray, then the bindings all cease to function. Likewise if I try and do removeAll() from rollArray and then push in a object of default values, then the bindings are immediately notified after removeAll and generate errors because they cannot find those properties inside of the array.
Is there a good way of solving this issue?
Current solution
It isn't elegant (and thus the reason for me asking here on SO) but currently I simply push a new element onto the modified array, then splice everything else off.
appViewModel.rollArray.push({
diceAmount: ko.numericObservable(1),
diceType: ko.observable(null),
diceAddition: ko.numericObservable(0),
diceMultiplication: ko.numericObservable(1)
});
appViewModel.rollArray.splice(0,appViewModel.rollArray().length-1);
Upvotes: 0
Views: 214
Reputation: 43881
Instead of push/splice, you can just re-assign the array value:
appViewModel.rollArray([{
diceAmount: ko.numericObservable(1),
diceType: ko.observable(null),
diceAddition: ko.numericObservable(0),
diceMultiplication: ko.numericObservable(1)
}]);
Upvotes: 2