I have a group of flags
- checkbox A
- checkbox B
- flag C
Generated with foreach data binding:
<input type="checkbox" data-bind="value: id, checked: $root.chkboxSelected" />
which take their controlled state from the observed array. Thus, when checking the field, the corresponding value is added to the array, the standard class knockoutjs, which works fine. Then I wanted to add a simple rule:
if C is checked, then it is also necessary to check A and B.
What is the cleanest way to add this logic to a knockout? I tried with a write ability that can be calculated:
var viewModel = { foo: observableArray(), .. }; viewModel.chkboxSelected = ko.computed({ read: function() { return this.foo(); }, write: function(value){ //add it if not added already if($.inArray(value, this.foo()) < 0) { this.foo.push(value); } // if C is present then A,B must be as well if($.inArray("C", this.foo()) >= 0) { if($.inArray("B", this.foo()) < 0) { this.foo().push("B"); } if($.inArray("A", this.foo()) < 0) { this.foo().push("A"); } } }, owner: viewModel });
Putting a breakpoint on the read and write functions: reading calls and the page loads fine. However, when I then select any checkbox, I get the following error (the record breakpoint never hits):
knockout-2.0.0.debug.js:2297 Uncaught TypeError: Object function dependentObservable() { if (arguments.length > 0) { if (typeof options["write"] === "function") {
source share