In Javascript, creating knockout.js binding handlers can be done the following way:
ko.bindingHandlers.yourBindingName = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { // This will be called when the binding is first applied to an element // Set up any initial state, event handlers, etc. here }, update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { // This will be called once when the binding is first applied to an element, // and again whenever any observables/computeds that are accessed change // Update the DOM element based on the supplied values here. } };
However, if you use the same syntax in TypeScript if you have the knockout.js type definitions referenced, you will notice some nice red squigly lines under the “yourBindingName” part. This is because it is not in the bindingHandlers interface. To fix this you can add the new binding to the interface.
To do this, create a file with the .d.ts extension (for instance, myBindingHandlers.d.ts) and add the following code to it:
/// <reference path="typings/knockout/knockout.d.ts" /> interface KnockoutBindingHandlers { yourBindingName: KnockoutBindingHandler; }
This wil add your binding handler to the interface, and everything works and its typesafe too.