I am wondering if it is possible with knockoutjs to pass arguments when binding.
I am binding a list of checkboxes and would like to bind to a single computed observabl
The accepted answer is decent, but if you have a function that generates a ko.computed for each checkbox, you are adding unnecessary overhead with multiple anonymous computed observables, which adds up quickly when your checkbox lists exceed 4-5 options.
This is a simpler implementation of a bitwise scenario, but the computed function can be whatever need be.
Script:
var vm = function() {
var vm = this;
this.checkedList = ko.observableArray();
this.bitwiseValue = ko.computed({
read: function () {
return vm.checkedList().reduce(function (prev, curr) {
return prev | curr;
}, 0);
},
write: function (myVal) {
vm.checkedList.removeAll();
var placeValue = 1;
while(myVal > 0) {
if((myVal % 2) == 1) {
alert(placeValue);
vm.checkedList.push(placeValue.toString());
}
myVal = myVal >>> 1;
placeValue = placeValue * 2;
}
}
}, this);
}
ko.applyBindings(vm);
Example fiddle here: http://jsfiddle.net/i_vargas3/RYQgg/