Knockouts Typescript Extenders

Can someone give an example of the extension observed during knockout in typescript? Knockout Extender: http://knockoutjs.com/documentation/extenders.html

I have been using this version of knockout.d.ts since March 6, 2013 https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout

EDIT: Thanks so much! So for the extension, you just need to add the KnockoutExtenders interface so that typescript "allows" 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 the following:

 this.score = ko.observable(score).extend({ logChange: "score" }); 
+4
source share
2 answers

The interfaces in typescript are open, so you can add them in several places.

For example, numerical. You need to add this term to expanders, as well as to your observables. Here is an 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; }; 

Here you can see the full sample: https://github.com/basarat/ChessClock/blob/d82a565ac9720cce00c75f099fcf7003f496755a/ChessClock/ChessClock/www/main.ts

+4
source

Comment-based update: in this case, you just need to extend the interface separately to the definition file:

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

All Articles