1
votes

I'm new to JSON and knockout. I'm facing an issue which is that I have a dataset in JSON with for instance 10 booleans defined e.g.

IsHappy = true;
IsSad = false;
IsAngry = true;

etc. My ViewModel is created from the JSON string, and I bind values to the checkbox as such :-

<input type="checkbox" data-bind="checked: IsHappy"/>
<input type="checkbox" data-bind="checked: IsSad"/>
<input type="checkbox" data-bind="checked: IsAngry"/>

I convert the ViewModel back to JSON and ajax it to save to server.

This all works fine however I cannot figure out how to implement a 'select all' feature. I've read through the examples online (http://jsfiddle.net/rniemeyer/eT7xV/) which involves creating an observableArray and toggling the IsSelected() observable, but in my case how do I map different JSON attributes to the IsSelected() attribute, and likewise how does toggling the IsSelected() observable update the original JSON attribute.

I tried just setting the attr('checked') using jquery but doing so checks the box but does not update the ViewModel, which means when I converted it back to JSON and posted it to server side no changes were detected.

1

1 Answers

1
votes

You need to have an array of your property names (you can explicitly list them or you can collect them using Object.keys).

Then when your allSelected checkbook is checked you go through these array of property names and set them according to the newValue:

viewModel.allSelected.subscribe(function(newValue) {
    var _this = this;

    //var checkboexes = ['IsHappy', 'IsSad', 'IsAngry'];
    var checkboexes = Object.keys(_this).filter(function(k) { 
       return k.indexOf('Is') == 0; 
    });

    ko.utils.arrayForEach(checkboexes, function(banner) {        
       _this[banner](newValue); 
    });
}, viewModel);

Demo JSFiddle.