淘汰赛打字稿扩展程序 [英] Knockout typescript extenders
问题描述
有人可以在打字稿中发布一个在淘汰赛中扩展可观察的例子吗?淘汰赛扩展程序:http://knockoutjs.com/documentation/extenders.html
Could anyone please post an example of extending an observable in knockout in typescript? Knockout extender: http://knockoutjs.com/documentation/extenders.html
我从 2013 年 3 月 6 日开始使用这个版本的knockout.d.tshttps://github.com/borisyankov/DefinitelyTyped/tree/master/knockout
I am using this version of knockout.d.ts from march 6. 2013 https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout
非常感谢你!因此,要扩展您只需要"添加接口 KnockoutExtenders,以便打字稿允许"它.示例
Thank you very much! So to extend you 'just' need to add the interface KnockoutExtenders so that typescript will 'allow' it. Example
interface KnockoutExtenders {
logChange(target: any, option: string): KnockoutObservableAny;
}
ko.extenders.logChange = function (target, option) {
target.subscribe(function (newValue) {
console.log(option + ": " + newValue);
});
return target;
};
在视图模型内部声明如下:
Inside the viewmodel declare like this:
this.score = ko.observable(score).extend({ logChange: "score" });
推荐答案
打字稿中的接口是开放式的,因此您可以在多个位置添加它们.
Interfaces in typescript are open ended so you can add to them in multiple places.
例如数字.您需要将此成员应用于扩展程序以及您的可观察对象.例子如下:
For example of numeric. You need to app this member to extenders as well as your observables. Here is the example:
interface KnockoutExtenders {
numeric(target: any, precision: number): KnockoutObservableAny;
}
interface KnockoutObservableNumber {
extend(data: any): KnockoutObservableNumber;
}
ko.extenders.numeric = function (target: KnockoutObservableNumber, digits) {
var result = ko.computed({
read: function () {
var value = target();
var toret: string = value.toString();
if (toret.length < digits) {
toret = "0" + toret;
}
else if (toret.length > digits) {
toret = toret.substring(0, digits);
}
return toret;
},
write: target
});
result(target());
return result;
};
You can see a complete sample here : https://github.com/basarat/ChessClock/blob/d82a565ac9720cce00c75f099fcf7003f496755a/ChessClock/ChessClock/www/main.ts
这篇关于淘汰赛打字稿扩展程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!