Knockout typescript extenders

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

Could anyone please post an example of extending an observable in knockout in typescript? Knockout extender: http://knockoutjs.com/documentation/extenders.html

I am using this version of knockout.d.ts from march 6. 2013 https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout

EDIT: 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" }); 

回答1:

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



回答2:

Update based on comment: In that case you just need to extend the interface separately to the definition file:

interface KnockoutExtenders {     logChange: (target: KnockoutObservableAny, option: string) => KnockoutObservableAny; } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!