在没有new关键字的情况下制作javascript基因剔除视图模型 [英] Making a javascript knockout viewmodel without the new keyword

查看:74
本文介绍了在没有new关键字的情况下制作javascript基因剔除视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览淘汰赛教程,所有示例都使用'new'关键字创建视图模型:

I'm looking through the knockout tutorials, and all the examples create the view model using the 'new' keyword:

//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计算的属性正常工作.到目前为止,这是我要提出的.

I'm trying to avoid using the new keyword, which usually works perfectly ok, but I find trouble getting the fullName computed property to work. This is what I've come up with so far.

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"不再引用传递给计算的函数内部的本地对象.我可以通过创建一个变量并在附加计算所得的函数并将其返回之前存储视图模型来解决此问题,但是如果存在更优雅,更紧凑的解决方案,则不需要我确保彼此依赖的方法是以正确的顺序附加,我肯定会改用它.

...which obviously fails since 'this' no longer refers to the local object inside the function passed to computed. I could get around this by creating a variable and store the view model before attaching the computed function and returning it, but if there exists a more elegant and compact solution that doesn't require me to make sure that methods that depend on each other are attached in the correct order, I'd sure like to use that instead.

有更好的解决方案吗?

推荐答案

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

When creating it in a function, it is not necessary to return a new object. Instead you would do:

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

现在您可以在计算出的可观察范围内访问适当的属性.

Now you have access to the proper this in the computed observable.

如果您真的不想使用新"(没有理由在这种情况下不应该使用),则可以执行以下操作:

If you really do not want to use "new" (there is no reason why you should not in this case), then you could do something like:

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;
};

这篇关于在没有new关键字的情况下制作javascript基因剔除视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆