我正在尝试制作一个演示以使用knockout-es5 插件来简化使用显示模块模式的模型。ViewModel1 是原始的 Knockout 模型,它工作正常。ViewModel2 是尝试使用 knockout-es5 插件。遇到一些事情
- 计算的属性不起作用,因为没有跟踪局部变量(例如 fullName1)。我可以使用 ko.defineProperty,但首先它与其他属性分开,其次必须使用 this.propertyName。
- 由于同样的原因(例如 doSomething),成员函数所做的更改可能没有反映出来。再次使用 this.propertyName 有效,但违反了 RM 模式。
var NS = NS || {};
$(function () {
NS.ViewModel1 = function (first, last) {
var
firstName = ko.observable(first),
lastName = ko.observable(last),
fullName = ko.computed(function () {
return firstName() + " " + lastName();
}),
doSomething = function (n) {
lastName(lastName() + " " + n);
}
;
return {
firstName: firstName,
lastName: lastName,
fullName: fullName,
doSomething: doSomething
};
};
NS.ViewModel2 = function (first, last) {
var
firstName = first,
lastName = last,
fullName1 = ko.computed(function () {
// Changed values are not reflected
return firstName + " " + lastName;
}),
fullName2 = ko.computed(function () {
// Should not work
return this.firstName + " " + this.lastName;
}),
doSomething = function (n) {
// Doesn't work
lastName += " " + n;
// Works
// this.lastName += " " + n;
}
;
var retObj = {
firstName: firstName,
lastName: lastName,
fullName1: fullName1,
fullName2: fullName2,
doSomething: doSomething
};
ko.track(retObj);
ko.defineProperty(retObj, 'fullName3', function () {
// Changed values are not reflected
return firstName + " " + lastName;
});
ko.defineProperty(retObj, 'fullName4', function () {
// Works
return this.firstName + " " + this.lastName;
});
return retObj;
};
var vm1 = new NS.ViewModel1("John", "Doe");
ko.applyBindings(vm1, document.getElementById("observableSection"));
var vm2 = new NS.ViewModel2("Jane", "Doe");
ko.applyBindings(vm2, document.getElementById("withoutObservableSection"));
setTimeout(function () {
vm1.firstName("John 1");
vm2.firstName = "Jane 1";
}, 2000);
setTimeout(function () {
vm1.doSomething(2);
vm2.doSomething(2);
}, 4000);
});