I'm not sure if this is the most efficient option - but it is fairly simple and works for me. The ko.computed returns an observable array as below:
self.computedArrayValue = ko.computed(function() {
var all = ko.observableArray([]);
....
return all();
});
A working example of the code:
Html:
<div data-bind="foreach: days">
<button class="btn btn-default btn-lg day" data-bind="text: $data, click: $root.dayPressed"></button>
</div>
Javascript function on the view model:
self.days = ko.computed(function() {
var all = ko.observableArray([]);
var month = self.selectedMonth(); //observable
var year = self.selectedYear(); //observable
for (var i = 1; i < 29; i++) {
all.push(i);
}
if (month == "Feb" && year % 4 == 0) {
all.push(29);
} else if (["Jan","Mar","May","Jul","Aug","Oct","Dec"].find((p) => p == month)) {
[29,30,31].forEach((i) => all.push(i));
} else if (month != "Feb") {
[29,30].forEach((i) => all.push(i));
}
return all();
});
listA
orlistB
will entirely replace the array itself instead of updating its contents (which is what we want in 99% of the cases). This means that you should not bind views to this observable. In effect, this code is as useful as its non-computed variant. See other answers for different approaches. – Vale