尝试使用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()) { ... }
...产生“意外令牌(”
答案 0 :(得分:2)
请参阅以下jsFiddle:http://jsfiddle.net/JD7fL/。
ko.computed
的函数参数不需要将givenName
和firstName
作为参数。您可以简单地引用要在计算函数中使用的字段。但是,因为在对象中有fullName
而不是构造函数,所以无法引用这些字段。我将self.identity
拆分为新的Identity
构造函数。
意外令牌错误是Employee
末尾流氓关闭的结果。
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());
<div data-bind="with: identity">
<div data-bind="text: fullName"></div>
</div>