typescript 在打字稿中声明可观察的淘汰赛
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16683961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring a knockout computed observable in typescript
提问by Kieran
I am new to typescript and would like to combine it with the goodness of knockout. I have a computed observable, which currently works, but want to know is this the right way about it or is there a better way.
我是打字稿的新手,想将它与淘汰赛的优点结合起来。我有一个计算出的 observable,它目前有效,但想知道这是正确的方法还是有更好的方法。
I am using the knockout definition file from nu-get. In it there are 4 KnockoutComputed(x) definitions.
我正在使用nu-get的淘汰赛定义文件。其中有 4 个 KnockoutComputed(x) 定义。
- KnockoutComputed
- KnockoutComputedDefine
- KnockoutComputedFunctions
- KnockoutComputedStatic
- 淘汰赛
- KnockoutComputedDefine
- KnockoutComputedFunctions
- KnockoutComputedStatic
I like the {} method of declaring observable's and would like to keep this. So long story short is this the correct method of declaring observables or is there an alternate way (maybe with intlisense in the function)
我喜欢声明 observable 的 {} 方法,并希望保留它。长话短说,这是声明 observable 的正确方法还是有替代方法(可能在函数中使用 intlisense)
I am using the first like so:
我正在使用第一个:
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();
}
});
}
}
with the html snippet of:
使用以下 html 片段:
<h2>Type Script and Knockout.</h2>
<input data-bind="value: firstname" />
<input data-bind="value: lastname" />
<div data-bind="text: fullname"></div>
回答by basarat
Recommendation is to use arrow functions for computed. It will give you the desired intellisence as well:
建议使用箭头函数进行计算。它也会为您提供所需的智能:
this.fullname = ko.computed({
owner: this,
read: () => {
return this.firstname() + " " + this.lastname();
}
});
Basically that captures this
using closure so it doesn't matter who calls back the function. this
will continue to mean PersonViewModel
instead of any
. More : http://basarat.github.io/TypeScriptDeepDive/#/this
基本上,this
使用闭包捕获,所以谁回调函数并不重要。this
将继续表示PersonViewModel
而不是any
。更多:http: //basarat.github.io/TypeScriptDeepDive/#/this
Try the intellisense in TypeScript Playground. You should get intellisense when you press this.
在TypeScript Playground 中尝试智能感知。当你按下时你应该得到智能感知this.