我正在查看淘汰教程,所有示例都使用'new'关键字创建视图模型:
//from learn.knockoutjs.com
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
}
ko.applyBindings(new AppViewModel());
Run Code Online (Sandbox Code Playgroud)
我试图避免使用new关键字,这通常可以正常工作,但我发现使fullName computed属性工作有困难.这是我到目前为止所提出的.
function makeViewModel() {
return {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington"),
fullName: ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this) };
}
ko.applyBindings(makeViewModel());
Run Code Online (Sandbox Code Playgroud)
...显然失败,因为'this'不再引用传递给compute的函数内的局部对象.我可以通过创建变量并在附加计算函数并返回它之前存储视图模型来解决这个问题,但是如果存在更优雅和紧凑的解决方案,则不需要我确保相互依赖的方法是按照正确的顺序附上,我肯定想用它来代替.
有更好的解决方案吗?