So there is this new thing called TypeScript. Which is a pretty cool superset of plain old javascript that adds type support and with that a whole bunch more cool stuff like classes, interfaces and modules.
I like to use KnockoutJS for my pages, because.. well, it makes working with data-driven pages super easy! I also want to take advantage of all the cool stuff that TypeScript brings.
This example is by no means a finished and polished one, but it will get you started with Knockout and TypeScript. Lets take a look at the very basic test ViewModel (in TypeScript of course).
module VM { declare var ko: any; export class Test { constructor (targetElement: HTMLElement) { ko.applyBindings(this, targetElement); } public Name: any = ko.observable(); public NewName: any = ko.observable(); public ChangeName() { this.Name(this.NewName()); } } }
I’ll point out one of the flaws that still need fixing in this example and that is the ANY keyword for knockout and its observables. By saying that something is of type any you lose all the type resolution that TypeScript gives us. If we look past that for now we have a fully functional Knockout viewmodel. Here is the HTML that goes with it:
<script type="text/javascript" src="~/Scripts/TypeScript/VM.js"></script> <script type="text/javascript"> var testVm = new VM.Test(document.getElementById('testVmView')); </script> <div id="testVmView"> <div> <p data-bind="text: Name"></p> </div> <div> <input type="text" data-bind="value: NewName" /><button data-bind="click: ChangeName">Change</button> </div> </div>
One way to fix the any typing of the observables is we provide our own wrapper around knockout observable and let the wrapper provide type safe observables.