Search code examples
knockout.jsknockout-2.0knockout-validation

Can computed be an observable too in KnockoutJS


I have first name and last name as an observable, username is computed. Is it possible to make username observable too ?


Solution

  • A computed in Knockout is already a type of observable. If what you want to be able to do is set the value of a computed then you can do so using the read and write properties.

    Here's a very crude example of setting the first and last name:

    var fn = ko.observable("Jimbo");
    var ln = ko.observable("Jangles");
    
    var vm = {
        myComputed : ko.computed({
            read: function () { return fn() + " " + ln(); },
            write: function (value) {
                var pieces = value.split(" ");
                fn(pieces[0]);
                ln(pieces[pieces.length -1]);
            }
        })
    };
    

    Here's a working example:http://jsfiddle.net/xxkLs0p8/