【问题标题】:TypeScript Class as ViewModel using Knockout?TypeScript 类作为 ViewModel 使用 Knockout?
【发布时间】:2015-09-13 01:23:54
【问题描述】:

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

function MyViewModel() {
    var self = this;

    self.MyObservable = ko.observable();

}

ko.applyBindings(new MyViewModel());

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

class MyViewModel {

}

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

谢谢

【问题讨论】:

标签: javascript mvvm knockout.js typescript


【解决方案1】:

是的,在我的许多项目中,我将 TypeScript 用于我的 KO 视图模型。 以下打字稿:

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

呈现以下有效视图模型:

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" 会失败)。

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

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

渲染:

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

【讨论】:

  • 谢谢我正在寻找的东西。
猜你喜欢
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2013-05-24
  • 2018-08-11
  • 2012-12-18
相关资源
最近更新 更多