17 April, 2012

Binding a DOM element to an observable using Knockout.js

I've been doing a bit of experimenting with Knockout.js recently. Having written quite a bit of .NET code over the years, I am very used to thinking in (and I prefer thinking in) the MVVM pattern when it comes to UIs, and so Knockout.js is nice.

And, as always, when writing code and living in the real world you sometimes need to do things that do not quite fit the pattern. In this case, I needed to draw on a canvas from my view model whenever some observables on it changed. The pragmatic thing to do when you need to draw on a canvas is to just grab the canvas by ID or whatever, but since this canvas lived in a template, identifying it through selectors quickly got messy (and hard).

Binding to it seemed like a much better idea, so I created the simple `element` Knockout.js binding. This is a one-way-to-source binding (.NET guys will be familiar with this terminology), meaning that the binding only writes to the view model from the view. In addition, the binding only does this once (when it is initialized), as the element will stay for the lifespan of the page.

So, in all its glory, here is my Knockout.js `element` binding:

Use it as you would any other binding:

<canvas width="100" height="60" data-bind="element: yourObservable"></canvas>

Simple as that. Now go use it!

No comments:

Post a Comment