我是打字稿的新手,并希望将其与淘汰赛的优点结合起来。我有一个计算的observable,它目前有效,但想知道这是正确的方法还是有更好的方法。
我正在使用knockout definition file from nu-get。其中有4个KnockoutComputed(x)定义。
我喜欢声明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>
答案 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.