gpt4 book ai didi

javascript - 在没有new关键字的情况下制作javascript基因 knockout View 模型

转载 作者:行者123 更新时间:2023-12-03 09:44:36 25 4
gpt4 key购买 nike

我正在浏览 knockout 教程,所有示例都使用'new'关键字创建 View 模型:

//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());

我试图避免使用new关键字,该关键字通常可以正常运行,但是我发现很难使fullName计算的属性正常工作。到目前为止,这是我想出的。
function makeViewModel() {
return {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington"),
fullName: ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this) };
}
ko.applyBindings(makeViewModel());

...这显然失败了,因为“this”不再引用传递给计算的函数内部的本地对象。我可以通过创建一个变量并在附加计算后的函数并将其返回之前存储 View 模型来解决此问题,但是如果存在更优雅,更紧凑的解决方案,则不需要我确保彼此依赖的方法是以正确的顺序附加,我肯定会改用它。

有更好的解决方案吗?

最佳答案

在函数中创建它时,不必返回新对象。相反,您可以这样做:

var ViewModel = function() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
this.firstName() + " " + this.lastName();
}, this);
};

现在,您可以在计算出的可观察值中访问适当的对象。

如果您真的不想使用"new"(没有理由在这种情况下不应该使用),则可以执行以下操作:
var createViewModel = function() { 
var result = {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington")
};

result.fullName = ko.computed(function() {
return result.firstName() + " " result.lastName();
});

return result;
};

关于javascript - 在没有new关键字的情况下制作javascript基因 knockout View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9744094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com