繁体   English   中英

使用Knockout将TypeScript Class作为ViewModel?

[英]TypeScript Class as ViewModel using Knockout?

我目前正在创建这样的Knockout ViewModel,

function MyViewModel() {
    var self = this;

    self.MyObservable = ko.observable();

}

ko.applyBindings(new MyViewModel());

有没有办法将此TypeScript类用作ViewModel?

class MyViewModel {

}

我知道TSC最终会生成一个函数,但是为了坚持TypeScript约定,我想知道它是否可能?

谢谢

是的,在我的许多项目中,我使用TypeScript作为我的KO视图模型。 以下TypeScript:

class MyViewModel {
    MyObservable = ko.observable();
    MyComputed = ko.computed(() => {
        return this.MyObservable() * 2;
    })
}

呈现以下有效的viewmodel:

var MyViewModel = (function () {
    function MyViewModel() {
        var _this = this;
        this.MyObservable = ko.observable();
        this.MyComputed = ko.computed(function () {
            return _this.MyObservable() * 2;
        });
    }
    return MyViewModel;
})();

但是在使用功能时要小心; 以下TypeScript函数:

MyFunction() {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
}

将呈现:

MyViewModel.prototype.MyFunction = function () {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
};

这意味着你可能会遇到的范围问题与this ,当你在你的例如结合直接使用该功能( data-bind="click: MyFunction"会失败)。

要防止出现这些范围问题,您应该将viewmodel中的函数声明为lambas:

MyFunction = () => {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
}

呈现:

    this.MyFunction = function () {
        if (_this.MyComputed() > 4) {
            alert('Higher than 4');
        }
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM