Knockout checked binding issue

I'm having a problem with checkbox bindings not quite working with KnockoutJS 2.0. I have an array of objects. One of the properties of those objects is an array of different objects. In the child objects there are a few properties, one of which is a boolean. I build a list for each parent object and under each parent I show the children. For each list of children I have two views, a read only and an edit view. In the read only I have images that represent whether or not the item is checked based on the boolean property. This works and if I update the boolean value through the console, I'm seeing what I would expect--the image goes away or displays based on the value I assign. In the edit view, the images are replaced with a checkbox. I see the same behavior when I update the value through the console--it is checked when I expect it to be and not when I don't. The problem comes in when I check or uncheck the checkbox. Doing this doesn't change the underlying value the checkbox is bound to.

Here's the basic idea of my data.

[
    {
        "xxx": "yyy",
        "xxx": "yyy",
        ...
        "Displays": [
            {
            "xxx": "yyy",
            ...
                "Excluded": false,
            },
            {
            "xxx": "yyy",
             ...
                "Excluded": true,
            }
        ],
    }
]

Here's the binding

<input type="checkbox" data-bind="checked: !Excluded()" />

Answers


the problem is that "checked" here is a bidirectional binding: the bound property needs to be read to generate the correct view, but needs also to be updated when you click on the checkbox. Contrast this to a binding like:

<span data-bind="text: 'your name is ' + name()"></span>

when the expression is only read, so you can use an expression (and you need to unwrap the observable).

So, you need to bind directly to the observable property, without "unwrapping" it adding '()', it will be done by knockout when needed, both for read and write:

<input type="checkbox" data-bind="checked: Excluded" />

See http://jsfiddle.net/saurus/usKwA/ for a simple example. Note how the checkbox labels are updated on change, showing that the model is updated and the rendering triggers correctly.

If you need to negate the value (so that the checkbox is checked when the value is false), you can add a writeable computed observable, as explained on http://knockoutjs.com/documentation/computedObservables.html section "Writeable computed observables", or you can negate the data in the viewmodel, doing it on the server just before sending the data, or on the client before populating the viewmodel.

hope this helps.


I know my answer is a bit late to the game here, but I had this problem today and this was the closest thread I could find related to the problem, and it doesn't seem to have an answer that solves it. So here's my solution.

Essentially, the issue is that knockout really wants your viewModel values to be a string, not a boolean, but this isn't always practical. So, I created a binding called "isChecked" which works strictly with booleans. Note: This will only work with observable properties.

ko.bindingHandlers.isChecked = {
    getElementDeclaredValue: function (element) {
        var declaredValue = element.getAttribute("value");

        // If a value is provided, we presume it represents "true",
        // unless its explicitly "false". If no value is provided, we
        // presume that a checked state would equal "true".
        return declaredValue && Boolean.isBool(declaredValue)
            ? Boolean.parse(declaredValue)
            : true;
    },

    init: function (element, valueAccessor) {
        var updateHandler = function () {
            var declaredValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
            var elementValue = element.checked ? declaredValue : !declaredValue;

            var modelValue = valueAccessor();
            var currentValue = ko.utils.unwrapObservable(modelValue);

            if (elementValue === currentValue)
                return;

            if (ko.isObservable(modelValue)) {
                modelValue(elementValue);
            }
        };

        ko.utils.registerEventHandler(element, "click", updateHandler);
    },

    update: function (element, valueAccessor) {
        var elementValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
        element.checked = elementValue === ko.utils.unwrapObservable(valueAccessor());
    }
};

The two Boolean methods ("parse" and "isBool") are defined as follows:

Boolean.isBool = function (value) {
    return (/^(?:true|false)$/i).test(value);
};

Boolean.parse = function (value) {
    return (/^true$/i).test(value);
};

I'll ignore any comments that say I shouldn't be modifying a built-in object prototype; I'll do as I damn well please ;-).

Usage is the same as the checked binding. The "value" attribute is optional, unless you want the checked state to represent false:

<input type="radio" id="rbNewClaim" name="ClaimType" value="false" data-bind="checked: isExistingClaim" />

Hope this helps someone.


I gave up trying to get this to work with the bool values and created an array of selected objects and handled it that way. It isn't the optimal solution, but I was tired of fighting this.


Need Your Help

Serializing XML data to store in MySQL with PHP

php mysql xml serialization storage

I have a series of very complex XML files. I need to access these often, so reading .xml files is something of a hangup. I've been considering writing a series of massive SQL statements, but befo...

How to make a grid-like listbox in xaml

c# xaml windows-runtime grid windows-phone-8.1

How can I make a mosaic-like listbox where data can be entered like any other listbox, and that can adapt to virtually any screen resolution?