Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement checkbox dependencies in knockoutjs

I have a group of checkboxes

  • checkbox A
  • checkbox B
  • checkbox C

Generated with the foreach data binding:

<input type="checkbox" data-bind="value: id, checked: $root.chkboxSelected" />

Which take their checked state from an observableArray. So checking a box will add the corresponding value to the array, standard knockoutjs that works fine. I then wanted to add a simple rule:

if C is checked, then A and B must be checked as well.

What is the cleanest way to add this kind of logic in knockoutjs? I tried with a writable computable observable:

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: read gets called and the page loads fine. However, when I then click any checkbox I get the following error (the write breakpoint never gets hit):

knockout-2.0.0.debug.js:2297

Uncaught TypeError: Object function dependentObservable() {
        if (arguments.length > 0) {
            if (typeof options["write"] === "function") {
                // Writing a value
                var valueForThis = options["owner"] || evaluatorFunctionTarget; // If undefined, it will default to "window" by convention. This might change in the future.
                options["write"].apply(valueForThis, arguments);
            } else {
                throw "Cannot write a value to a dependentObservable unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.";
            }
        } else {
            // Reading the value
            if (!_hasBeenEvaluated)
                evaluateImmediate();
            ko.dependencyDetection.registerDependency(dependentObservable);
            return _latestValue;
        }
    } has no method 'push'
like image 793
dgorissen Avatar asked Feb 10 '12 13:02

dgorissen


1 Answers

When the checked binding is bound against an array, then it needs to be able to perform array operations against it. So, using a writeable computed observable in that case will cause an issue.

However, you can opt to use a manual subscription to keep your items in sync.

Here is a sample view model:

var ViewModel = function() {
    var self = this;
    this.items = ko.observableArray([
        { id: "A" },
        { id: "B" },
        { id: "C" },
        { id: "D" }
        ]);
    this.checked = ko.observableArray();
    this.checked.subscribe(function(newValue) {
        if (self.checked.indexOf("C") > -1) {
            if (self.checked.indexOf("A") < 0) {
               self.checked.push("A");
            }  
            if (self.checked.indexOf("B") < 0) {
               self.checked.push("B");
            }  
        }
    });

    this.shouldBeDisabled = function(item) {
         return (item.id === "B" || item.id ==="A") && self.checked.indexOf("C") > -1;     
    };
};

Here is the view:

<ul data-bind="foreach: items">
    <li>
        <span data-bind="text: id"></span>
        <input type="checkbox" data-bind="attr: { value: id }, checked: $root.checked, disable: $root.shouldBeDisabled($data)" />
    </li>
</ul>

I used attr: { value: id } instead of value to avoid the event handler that would be attached by the value binding, as the value binding is designed to handle changes to a field. In this case, we only want to set the value attribute.

Sample here: http://jsfiddle.net/rniemeyer/tQJMg/

like image 185
RP Niemeyer Avatar answered Nov 10 '22 13:11

RP Niemeyer