Custom bindings

In Chapter 2, Creating a Simple Knockout.js Application, we examined a variety of standard Knockout.js bindings such as text, visible, click, submit, and so on. However, in a big application, this list may not be enough. Fortunately, you can define your own custom bindings.

Registering a new binding

Knockout.js provides us with the ko.bindingHandlers property to register new bindings. You can define a new subproperty of it as a JavaScript object with two callback properties: init and update. Let's take a look at the short binding registration template:

ko.bindingHandlers.newBindingName = { init: function(element, valueAccessor, allBindings) { // Called on first binding applying to an element // Set up any initial state }, update: ...

Get Getting Started with Knockout.js for .NET Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.