我有两个像这样的淘汰简单视图模型定义
function vm1() {
var self = this;
self.firstName = ko.observable('Bob');
self.lastName = ko.observable('Smith');
self.fullName = ko.computed(function() {
return self.firstName() + " " + self.lastName();
});
self.isBob = ko.computed(function() {
return self.firstName() == "Bob";
});
}
var vm2 = {
firstName: ko.observable('Bob'),
lastName: ko.observable('Smith'),
fullName: ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this),
isBob: ko.computed(function() {
return this.firstName() == "Bob";
}, this)
};
当我与vm1
绑定时,我的视图页面正常工作,否则vm2
控制台显示错误,如"undefined is not a function"
..我知道问题在于计算属性,最新的方法是在预定义的视图模型变量中声明计算属性,如vm2
。
这是我的html来完成细节
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>Full name: <strong data-bind="text: fullName, visible: isBob"></strong></p>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>