【问题标题】:Declaring a knockout computed observable in typescript在打字稿中声明一个淘汰赛计算的 observable
【发布时间】:2013-05-17 01:03:29
【问题描述】:

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

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

  1. 淘汰赛计算
  2. KnockoutComputedDefine
  3. KnockoutComputedFunctions
  4. KnockoutComputedStatic

我喜欢声明 observable 的 {} 方法,并希望保留它。长话短说,这是声明 observables 的正确方法还是有另一种方法(可能在函数中使用 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 sn-p:

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

【问题讨论】:

    标签: knockout.js typescript


    【解决方案1】:

    建议使用箭头函数进行计算。它也会为您提供所需的智能:

    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.时你应该得到智能感知

    【讨论】:

    • 嘿,这很酷,还有您发送的网站。 Visaul studio 中仍然没有智能感知。我是不是只能忍气吞声处理了。
    • 你绝对应该得到智能感知。试试我刚刚添加到答案中的游乐场链接。
    • 啊。我这里只安装了快递,也许这与它有关?我稍后会尝试使用propper vs install
    • 难道没有类似于 vue ts 中的@watch 的东西吗?使用 ES6 中的 get property() {}
    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2016-07-21
    • 2020-05-30
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    相关资源
    最近更新 更多