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

时间:2013-05-22 05:17:29

标签: knockout.js typescript

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

我正在使用knockout definition file from nu-get。其中有4个KnockoutComputed(x)定义。

  1. KnockoutComputed
  2. KnockoutComputedDefine
  3. KnockoutComputedFunctions
  4. KnockoutComputedStatic
  5. 我喜欢声明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();
                }
            });
        }
    }
    

    使用html片段:

    <h2>Type Script and Knockout.</h2>
    <input data-bind="value: firstname" />
    <input data-bind="value: lastname" />
    <div data-bind="text: fullname"></div>
    

1 个答案:

答案 0 :(得分:36)

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

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

基本上,使用闭包捕获this因此无论谁回调函数都无关紧要。 this将继续表示PersonViewModel而不是any。更多:http://basarat.github.io/TypeScriptDeepDive/#/this

TypeScript Playground中尝试智能感知。按this.

时,您应该获得智能感知