将值传递给KO计算对象内的observable

时间:2013-11-20 01:10:02

标签: javascript object knockout.js javascript-objects

尝试使用javascript将值暴露给对象内对象内的KO计算可观察对象。我目前正在页面上“未定义未定义”...

    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
  )};

尝试了各种选择并且越来越近了 - 请问有什么想法吗?

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

...产生“意外令牌(”

1 个答案:

答案 0 :(得分:2)

请参阅以下jsFiddle:http://jsfiddle.net/JD7fL/

ko.computed的函数参数不需要将givenNamefirstName作为参数。您可以简单地引用要在计算函数中使用的字段。但是,因为在对象中有fullName而不是构造函数,所以无法引用这些字段。我将self.identity拆分为新的Identity构造函数。

意外令牌错误是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>