Thursday, May 29, 2014

Knockout checkbox binding to string

As you know knockout has “checked” binding that allows you to bind your Boolean observable to a checkbox. But there may be situations where you will have your checked value as string, for example “yes”.

One approach for this is to define a computed observable and bind it to the checkbox. But the problem is for every checkbox you need to define a computed observable, which causes code bloating. Instead of this let’s create custom binding which accepts a string (yes/no) and binds the checkbox. Here is our code for this custom binding

    ko.bindingHandlers.customcheck = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {
            var value = valueAccessor();
            if (value().toLowerCase() === "yes")
                value(true);
            else
                value(false);

            ko.applyBindingsToNode(element, {
                checked: value
            });
        }
    };

As you see in the above code, I am actually changing the value of my observable. If you prefer you can define your own computed observable inside this custom binding and use it, so that you don’t have to change your observable.

    ko.bindingHandlers.customcheck = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {
            var value= valueAccessor();
            var checkbool = ko.computed({
                read: function () { return (value().toLowerCase() === "yes"); },
                write: function (boolvalue) { value(boolvalue ? "Yes" : "No"); }
            });

            ko.applyBindingsToNode(element, {
                checked: checkbool
            });
        }
    };

Either of the above approaches will let you bind your checkbox to a string value.

No comments:

Post a Comment