Monday, October 2, 2017

Knockout options group binding with JS objects

If we need to bind complex JS objects to select HTML element in knockout with optgroups then the following jsfiddle has great sample

http://jsfiddle.net/rniemeyer/aCS7D/

so the HTML binding looks like:

<select data-bind="foreach: groups, value: selectedOption">
    <optgroup data-bind="attr: {label: label}, foreach: children">
        <option data-bind="text: label, option: $data"></option>
    </optgroup>
</select>

       
<hr />

<div data-bind="text: specialProperty"></div>

and js code looks like:

ko.bindingHandlers.option = {
    update: function(element, valueAccessor) {
       var value = ko.utils.unwrapObservable(valueAccessor());
       ko.selectExtensions.writeValue(element, value); 
    }       
};

function Group(label, children) {
    this.label = ko.observable(label);
    this.children = ko.observableArray(children);
}

function Option(label, property) {
    this.label = ko.observable(label);
    this.someOtherProperty = ko.observable(property);
}

var ViewModel = function() {
    this.groups = ko.observableArray([
        new Group("Group 1", [
            new Option("Option 1", "A"),
            new Option("Option 2", "B"),
            new Option("Option 3", "C")
        ]),
        new Group("Group 2", [
            new Option("Option 4", "D"),
            new Option("Option 5", "E"),
            new Option("Option 6", "F")
        ])
    ]);

    this.selectedOption = ko.observable();

    this.specialProperty = ko.computed(function(){
        var selected = this.selectedOption();
        return selected ? selected.someOtherProperty() : 'unknown';
    }, this);
};

ko.applyBindings(new ViewModel());

No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...