在打字稿中声明敲除计算可观察
问题描述:
我是打字稿的新手,并希望将其与淘汰赛的优点结合起来。我有一个计算可观察值,目前可行,但想知道这是否正确或有更好的方法。我正在使用knockout definition file from nu-get。其中有4个KnockoutComputed(x)定义。在打字稿中声明敲除计算可观察
- KnockoutComputed
- KnockoutComputedDefine
- KnockoutComputedFunctions
- KnockoutComputedStatic
我喜欢观察到申报的的{}方法,并想保持这一点。所以长话短说,这是宣布可观的正确方法还是有一种替代方法(也许在功能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>
答
建议使用箭头函数进行计算。它会给你想要的intellisence还有:
this.fullname = ko.computed({
owner: this,
read: () => {
return this.firstname() + " " + this.lastname();
}
});
基本上,使用封闭所以也无所谓谁回调函数捕获this
。 this
将继续意味着PersonViewModel
而不是any
。更多:http://basarat.github.io/TypeScriptDeepDive/#/this
尝试intellisense在TypeScript Playground。当你按下this.
你应该得到intellisense嘿,这很酷,也是你发送的网站。在签证stuidio仍然没有智力。我只是不得不把它吸收并处理。 – Kieran
你一定要获得智能感知。试试刚添加到答案中的操场链接。 – basarat
啊。我只在这里安装了快递,也许这与它有关系?我会稍后用propper和install来尝试 – Kieran