Knockout Computed ObservableArray Subscription
SO-Question
HTML
<label>Multiple Toppings:
<input type="checkbox" data-bind="checked: multiselectable" />
<em data-bind="if: !multiselectable()">pick only one topping</em>
</label>
<h2>Available</h2>
<ul data-bind="foreach: toppings">
<li data-bind="text: label, click: selected.bind($data, true)"></li>
</ul>
<h2>Selected</h2>
<ul data-bind="foreach: selectedToppings">
<li data-bind="text: label, click: selected.bind($data, false)">
</li>
</ul>
<h2>TEST</h2>
<ul data-bind="foreach: stuff">
<li data-bind="text: $data, click: $root.testFunc">
</li>
</ul>
JavaScript
function Topping(options) {
this.label = ko.observable(options.label);
this.selected = ko.observable(false);
}
var iceCream = {
toppings: ko.observableArray([
new Topping({label: 'Sprinkles'}),
new Topping({label: 'Marshmallows'}),
new Topping({label: 'Nuts'})
]),
multiselectable: ko.observable(false)
};
iceCream.selectedToppings = ko.computed(function () {
return ko.utils.arrayFilter(iceCream.toppings(), function(item){
return item.selected();
});
});
iceCream.arr = [1,2,3];
iceCream.stuff = ko.computed(function() {
return iceCream.arr;
})
iceCream.testFunc = function() {
iceCream.arr.push(iceCream.arr.length());
}
var selectedSub = iceCream.selectedToppings.subscribe(function (toppings) {
if (!this.multiselectable()) {
if (toppings.length > 1) {
var item = toppings.shift();
item.selected(false);
}
}
}, iceCream);
ko.applyBindings(iceCream);
alert(typeof iceCream.selectedToppings());