Skip to content
This repository was archived by the owner on Sep 18, 2026. It is now read-only.
Elias Skogevall edited this page Jan 20, 2022 · 2 revisions

Syntax

Bindinghandlers

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.

class MyBindingHandler implements ko.BindingHandler<...> { ... }
ko.bindingHanders.myBindingHandler = new MyBindingHandler()

// ES6 class exports
export { MyBindingHandler }
export = MyBindingHandler
export default MyBindingHandler

Transform Child Context

In the rare event the binding handler creates a new child context, the binding should specify the method transformContext.

class BindingHandler implements ko.BindingHandler<...> {
  init(element, valueAccessor, allBindings, viewModel, bindingContext) {
    // Make a modified binding context, with a extra properties, and apply it to descendant elements
    const innerBindingContext = bindingContext.extend(valueAccessor);
    ko.applyBindingsToDescendants(innerBindingContext, element);

    // Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
    return { controlsDescendantBindings: true };
  }

  transformContext!: (input: Input, context: ParentContext) => ChildContext
}

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.

<!-- ko-import { myBindinghandler } from './myBindinghandler' -->
<p data-bind="myBindinghandler: ...">

Viewmodels

Defining & exporting viewmodels

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.

// ES6 class exports
export class ViewModel { ... }
export = class ViewModel { ... }
export default class ViewModel { ... }

// Singleton exports
export = new ViewModel()
export default new ViewModel()

Using viewmodels

The ko-import directive uses the same syntax as ES6, but with a different prefix. The importing of the viewmodel is separate from the declaration of the viewmodel. The ko-viewmodel directive is used to set the current viewmodel. It can also be a globally defined type/interface/class.

TIP! The ko-viewmodel directive can be used multiple times in the same view to re-define the viewmodel.

Class default import
<!-- ko-import ViewModel from './viewmodel' -->
<!-- ko-viewmodel ViewModel -->

Singleton typeof import
<!-- ko-import * as ViewModel from './viewmodel' -->
<!-- ko-viewmodel typeof ViewModel -->

Globally defined viewmodel
<!-- ko-viewmodel GobalViewModel -->

Clone this wiki locally