声明敲击计算出打字稿中的observable

Kie*_*ran 19 knockout.js typescript

我是打字稿的新手,并希望将它与淘汰赛的优点结合起来.我有一个计算的observable,目前有效,但想知道这是正确的方法还是有更好的方法.

我正在使用nu-get淘汰定义文件.其中有4个KnockoutComputed(x)定义.

  1. KnockoutComputed
  2. KnockoutComputedDefine
  3. KnockoutComputedFunctions
  4. KnockoutComputedStatic

我喜欢声明observable的{}方法,并希望保留它.长话短说这是正确的方法来声明可观察量,还是有另一种方式(可能在函数中使用intlisense)

我正在使用第一个:

class PersonViewModel {
    public firstname: KnockoutObservable<string>;
    public lastname: KnockoutObservable<string>;
    public fullname: KnockoutComputed<string>;
    constructor() {
        this.firstname = ko.observable('');
        this.lastname = ko.observable('');
        this.fullname = ko.computed({
            owner: this,
            read: function () {
                return this.firstname() + " " + this.lastname();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

使用html片段:

<h2>Type Script and Knockout.</h2>
<input data-bind="value: firstname" />
<input data-bind="value: lastname" />
<div data-bind="text: fullname"></div>
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 38

建议使用箭头函数进行计算.它也会给你所需的智慧:

this.fullname = ko.computed({
        owner: this,
        read:  () => {
            return this.firstname() + " " + this.lastname();
        }
    });
Run Code Online (Sandbox Code Playgroud)

基本上,this使用闭包捕获所以谁回调函数无关紧要.this将继续意味着PersonViewModel而不是any.更多:http://basarat.github.io/TypeScriptDeepDive/#/this

TypeScript Playground中尝试intellisense .按下时应该得到intellisensethis.