Alternative Approach to Extenders in Knockout.js

Categories: Uncategorized

ko.observable.fn.booleanValue = function () {
    var formattedValue = ko.computed({
        read: function () {
            if (this() === true) return "True";
            else if (this() === false) return "False";
        },
        write: function (newValue) {
            if (newValue) {
                if (newValue === "False") this(false);
                else if (newValue === "True") this(true);
            }
        }
    }, this);

    this.formattedValue = formattedValue;
    this.formattedValue(this());
    return this;
};

This code is an alternative to the previous post of how to do an extender for a Boolean value.  It works exactly like the extender, but instead attaches functionality to the .fn extension point of ko.observable.  To use this, do the following:

this.wantsFriesWithThat = ko.observable(true).booleanValue();
This is a bit cleaner than using the extend() method.  If we wanted, we could send in parameters to further configure how this extension works, we could simply pass them to the booleanValue() function.  If you want to add another extender, you would simply chain another onto the call to booleanValue().  This is why the function returns this because the this in the function refers to the observable itself.

No Comments