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. You start with a plain HTML template, create a JavaScript view model by combing/manipulating observable properties, and finally annotate the HTML template with declarative bindings. These bindings automatically reflect view model changes in the HTML and vice versa, greatly simplifying UI updates.

Often when building more complex applications, instead of repeating the same template and binding logic, you’ll want to isolate it as a unit of UI functionality and re-use it throughout your application. When starting out with Knockout.js, however, it’s not always obvious how to do this. In this post I’ll run through creating a pagination control as an example of how to create re-usable controls in Knockout.

Getting started

First of all, we need some markup to represent our paging control. Instead of dreaming up the markup for the control I’m going to try and keep this closer to real-life by making use of the Bootstrap version. According to the documentation, you can render the control with the following markup:

To go with this control we need something to page through. Let’s quickly add in an observableArray of items, a view model which wraps up the paging logic and a simple template to render the result:

At this point it’s important to point out that we’re not trying to encapsulate the logic for paging within the component, only the UI control for navigating the pages. Obviously, in a real application, the paging logic is going to be more complicated and navigating to the second page will most likely require a round-trip to the server or equivalent. This simplistic version is just to keep the example easy to follow for this post.

The basic control

To start with we’ll create the basic control in-place and then once we have that working, we’ll extract it out into a reusable component. First things first, let’s wire up the next and previous button click handlers together with their enabled state to some simple bindings:

Then we need some bindings to display, and handle clicks on, the page number buttons themselves. Again they’re not too complicated:

Now we have ourselves a pretty basic, but functional paging control, so it’s time to try and create a reusable component out of it.

A template-based component

Templates are a fundamental part of Knockout. Since I’m sure you’ll have used them previously, I’ll skip over the basics here. However, if you want to know more, there’s plenty of documentation on the Knockout website.

Let’s create a template from the HTML in the previous step:

Now we can reference the template from our page using the follow virtual element binding:

This is a good start, since we now have a re-usable template for the HTML, but we haven’t really managed to encapsulate the full functionality of the control. If we were to use this component multiple times we’d still need n copies of the properties and handlers referenced by the template on our view models.

Instead, wouldn’t it be good if we could encapsulate the functionality so that all we needed on our view model were the following properties for controlling the visible items anyway:

  • The current page index (can be updated by the control to prompt navigation)
  • The total number of items
  • The number of items per page

To do this we’ll need to find a way of associating a helper view model with the template, and then having that view model itself bind on to the consumer’s view model. Luckily, a custom binding turns out to be a very neat way of achieving this.

A custom-binding based component

A custom binding allows us to associate custom functionality with a key to be used in a binding string. In this case we’d like to include the paging control with only the following custom binding:

Here we’ve added a layer of indirection to the itemCount, perPage and pageIndex properties to be good citizens. It would work fine if we just assumed properties of the correct name existed, but by allowing them to be mapped onto any view model properties we avoid imposing any naming constraints on our main view model.

To create this binding, we’re going to follow the guide on the Knockout website:

The code looks a bit complicated, but it’s really only delegating everything to the template binding with the exception of the valueAccessor argument. Instead of passing it through unchanged, we pass it through the makeTemplateValueAccessor function, which we’ll cover soon. The last line is a special instruction to Knockout, which tells it to allow the binding to be used within virtual elements.

The makeTemplateValueAccessor function allows us to control the template name and the view model that will be bound to that template:

If you look closely at the function you’ll see that instead of returning the configuration object, the function returns another function?! It is then the returned function itself, when called, that will return the configuration object?! This might seem a bit weird (and it is!), but it’s an implementation detail of Knockout that we just have to work with. Also, once you get used to the pattern, it’s not too bad. I think you can still see what’s going on and most importantly the configuration object is still clear.

The final piece of the puzzle is to create our references to the original view model properties via the configuration object that is passed in. Instead of just assuming the user will pass in observables, we’ll add some logic to allow raw values to be passed in as well. We’ll also make the control a little easier to debug by doing some sanity checking of the pageIndex property:

And there you have it, an easy to reference, re-usable Knockout component implemented using custom-bindings and virtual elements. If you’d like to see it in action, the final version is available on JSBin.


Hopefully this quick guide has shown you how to create a re-usable component in your next project. There’s plenty of documentation on creating custom bindings on the Knockout website and don’t forget that all of the official bindings use the same API, so now that you know the basics don’t be afraid to look into those for inspiration.

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

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: Chris Price, Javascript, Knockout, Knockout 3.0, Knockout.js, MVVM, Re-usable component,

Comments are closed.