Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

codeA guest post by Chris Price from Newcastle upon Tyne in the UK who spends his days at Scott Logic developing desktop and mobile web apps for financial services companies. He’s one of the creators of the open source PropertyCross project and has contributed to a number of other projects including KnockoutJS and TodoMVC. You can reach Chris at

Knockout.js is a JavaScript MV* framework that helps you build dynamic UIs using the Model-View-ViewModel (MVVM) pattern. Using Knockoutjs, you start with a plain HTML template, create a JavaScript view model by combing/manipulating observable properties and finally you annotate the HTML template with declarative bindings. These bindings automatically reflect view model changes in the HTML and vice versa, greatly simplifying UI updates. Be sure to read Creating a Basic Re-usable Component in Knockout 3.0, a post where I run through creating a pagination control as an example of how to create re-usable controls in Knockout.js.

Before Knockout.js 3.0, the binding syntax was very prescriptive. By default your bindings had to be defined within one data-bind attribute and the bindings themselves had to follow a pseudo JSON object literal syntax. Knockout 3.0 has introduced binding string and node preprocessing extension points that allow you to modify this behavior. In this blog post I’ll show you an example of node preprocessing and introduce a technique for diving deeper if you need to.

Multiple data-bind attributes

Once you’ve been working on your app for a little while, it’s almost inevitable that you’ll end up with at least one very complex (or long!) data-bind attribute. It is important to format the attribute across multiple lines. For example, in this highly contrived example (JSBin), I find it very difficult to parse out the individual bindings:

As stated above, this is a highly contrived example and there are a number of steps I would take to simplify this specific example if I was using it for real. I’d start by pulling the click handler back onto the view model which, as well as tidying things up, means the logic can then be unit tested. Then I’d move the class name lookup into a computed observable and use the alternative syntax for the CSS binding to reference that. If it subsequently turned out that this control was being reused across the application, I might even consider creating a control from it.

Ideally I’d prefer it if the bindings could be split across multiple attributes, which could themselves be formatted across multiple lines, to make the whole thing easier to read:

Helpfully, Knockout.js 3.0 provides the extension points to allow exactly this kind of customization of the binding provider. We’ll look into a couple of different techniques for achieving this.

Using preprocessNode to allow multiple data-bind attributes

Knockout.js 3.0 provides an extension point for preprocessing nodes before it attempts to parse the data-bind attribute. By hooking in at this point, the hard work of calling our function exactly once for every node, including those dynamically created by templates, is handled for us. All we need to provide is a method to manipulate the node as appropriate, optionally returning an array of additional nodes for Knockout.js to parse.

Here’s a basic implementation of a node preprocessor that can handle the multiple data-bind attributes from the previous code block:

First up we check to ensure that the node has attributes. This function will be called for all nodes in the DOM, including non-element nodes such as text nodes. We then iterate over the collection of attributes using an index-based for loop (because it’s a NamedNodeMap and not actually an array). If we find an attribute starting ‘data-bind-‘, we split off the binding key from the attribute name and concatenate that together with the binding value from the attribute value. Finally, we then create a ‘data-bind‘ attribute on the element containing all of the processed bindings concatenated together for processing by Knockout.js.

The good news is that this works! Our bindings are processed and the UI behaves as if we were using the data-bind attribute. The bad news is that after binding, the DOM looks even worse than it did before:

Setting the data-bind attribute on the element in addition to the existing data-bind- attributes is therefore not ideal! What we’d really like to do is change the Knockout.js processing itself rather than preprocess the node. In Knockout.js 3.0, as well as when customizing an existing bindingProvider as above, we can go one step further and create our own.

Using a custom bindingProvider to allow multiple data-bind attributes

All of the binding logic within Knockout is localised to an instance of ko.bindingProvider referenced at ko.bindingProvider.instance. It consists of the following methods:

  • nodeHasBindings(node) – Test to see if the node has bindings defined. Used to improve binding performance, not guaranteed to be called before getBindings/getBindingsAccessors.
  • getBindings(node, bindingContext) – Retrieve the bindings for this node given the supplied context.
  • getBindingAccessors(node, bindingContext) – Retrieve the binding accessors for this node given the supplied context. Basically, this returns the same as above, but with all values wrapped in a function() { return ...; } to allow Knockout.js to evaluate expressions. We won’t worry too much about this functionality, and just mirror the behavior of the default binding provider.

The first thing we need to do is wire in our replacement for the default binding provider:

The replacement binding provider is instantiated in place of the existing default provider. During construction we’ll grab a reference to a default binding provider implementation to make our implementation a bit simpler later on. We then have stub implementations of the 3 required methods that we’ll fill in below. Importantly, we do all of this before the ko.applyBindings call to ensure Knockout.js uses our binding provider and not the default one.

The core of the implementation is going to be very similar to the preprocessNode implementation. We’ll create a local helper method to interrogate a node for a binding string if one is present:

This method has 2 bits of additional functionality:

  • Instead of setting the derived binding string directly onto the data-bind attribute, we return it for processing by Knockout.js.
  • To simplify debugging, if the user attempts to mix both data-bind and data-bind-* attributes, we throw an error.

The final piece of the puzzle is to wire up the interface methods to this function:

You can see this code in action on JSBin. Be sure to checkout the DOM in the inspector to be sure the data-bind attribute is no more. The general pattern we’ve followed is to attempt to retrieve the binding string using the getBindingsString method. If this fails, we fall-back to using the default implementation equivalent. The rest of the implementation mirrors the functionality in the default implementation. By using this approach we can piggy-back on it’s caching, expression re-writing and error handling for free.


In this post I’ve introduced a new technique Knockout.js 3.0 enables for customizing the behavior of bindings and dived a little deeper to show a glimpse of the binding guts of Knockout.js. For some other great examples, check out the knockout.punches plugin by Michael Best, and don’t forget the examples in the documentation as well.

Look below for some great JavaScript resources from Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

JavaScript Enlightenment is for you if you’re an advanced beginner or intermediate JavaScript developer. It will solidify your understanding of the language—especially if you use a JavaScript library. In this concise book, JavaScript expert Cody Lindley provides an accurate view of the language by examining its objects and supporting nuances.
Learning JavaScript Programming Video teaches you the basics of programming with JavaScript, the worlds most used programming language. The tutorial is designed for the absolute beginner – no prior JavaScript programming experience is required in order to get the most out of this video training. You will start with learning what programming is, and specifically, what JavaScript is, how it it used, and its limitations. You will discover variables and data types, and how to take input and create output. Craig covers conditions, loops, arrays, sorting, functions, paramaters and debugging. You will even learn advanced concepts such as OOP, string manipulations, regular expressions and other programming patterns.
Eloquent JavaScript is a guide to JavaScript that focuses on good programming techniques rather than offering a mish-mash of cut-and-paste effects. The author teaches you how to leverage JavaScript’s grace and precision to write real browser-based applications. The book begins with the fundamentals of programming—variables, control structures, functions, and data structures—then moves on to more complex topics, like object-oriented programming, regular expressions, and browser events. With clear examples and a focus on elegance, Eloquent JavaScript will have you fluent in the language of the web in no time.

Tags: Binding preprocessing, data-bind, Javascript, Knockout, Knockout 3.0, Knockout.js, MVVM,

Comments are closed.