KOLint
Search…
Binding Handlers

Defining & exporting bindinghandlers

All ES6 exports, exporting a class or a instance of a class are supported. The exports has to be done in a TypeScript file, if not allowJs is enabled in current tsconfig. The binding handler should implement the Knockout BindingHandler interface.
1
class MyBindingHandler implements ko.BindingHandler<...> { ... }
2
ko.bindingHanders.myBindingHandler = new MyBindingHandler()
3
4
// ES6 class exports
5
export { MyBindingHandler }
6
export = MyBindingHandler
7
export default MyBindingHandler
Copied!

Transform Child Context

In the rare event the binding handler creates a new child context, the binding should specify the method transformContext.
1
class BindingHandler implements ko.BindingHandler<...> {
2
init(element, valueAccessor, allBindings, viewModel, bindingContext) {
3
// Make a modified binding context, with a extra properties, and apply it to descendant elements
4
const innerBindingContext = bindingContext.extend(valueAccessor);
5
ko.applyBindingsToDescendants(innerBindingContext, element);
6
7
// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
8
return { controlsDescendantBindings: true };
9
}
10
11
transformContext!: (input: Input, context: ParentContext) => ChildContext
12
}
Copied!

Using bindinghandlers

If the bindinghandler is not globally declared, the binding handler needs to be imported into the view using the same import syntax as for the viewmodels.
1
<!-- ko-import { myBindinghandler } from './myBindinghandler' -->
2
<p data-bind="myBindinghandler: ...">
Copied!
Last modified 4mo ago