Passing values to KO computed observable within an object

Trying to expose values to a KO computed observable within an object within an object using javascript. I’m currently getting “undefined undefined” on the page…

    function Employee () {            

        var self = this;

        self.identity = ko.observable({
            employeeTitle: ko.observable(""),
            titles: ko.observableArray(['Mr','Mrs','Ms']),
            givenName: ko.observable(""),
            lastName: ko.observable(""),
            otherNames: ko.observable(""),

            fullName: ko.computed(function(givenName,lastName){
                return givenName + " " + lastName;
            })

        });

           //rest of object
  )};

Have tried various options and am getting closer – any ideas out there please?

function(givenName(), lastName()) { ... }

…yields “unexpected token (“

Answer

Please see the following jsFiddle: http://jsfiddle.net/JD7fL/.

The function argument to ko.computed does not need to take givenName and firstName as arguments. You can simply reference the fields you want to use within the computed function. But, because you had fullName within an object instead of a constructor function, you couldn’t reference those fields. I split self.identity into a new Identity constructor.

The unexpected token error is a result of a rogue closing paren at the end of Employee.

JavaScript

function Employee () {            
    var self = this;

    self.identity = ko.observable(new Identity());
};

function Identity() {
    var self = this;

    self.employeeTitle = ko.observable("");
    self.titles = ko.observableArray(['Mr','Mrs','Ms']);
    self.givenName = ko.observable("John");
    self.lastName = ko.observable("Doe");
    self.otherNames = ko.observable("");

    self.fullName = ko.computed(function(){
        return self.givenName() + " " + self.lastName();
    });
}

ko.applyBindings(new Employee());

HTML

<div data-bind="with: identity">
    <div data-bind="text: fullName"></div>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *