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 http://github.com/chrisprice.

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. To learn more about Knockout.js, be sure to look at my Creating a Basic Re-usable Component in Knockout 3.0 and Binding Preprocessing in Knockout 3.0 posts, in addition to this one.

Knockout 3.0 introduces a number of improvements in the binding pipeline, including a number of extension points for pre-processing binding values. For those just starting out and even those more experienced with MVVM, debugging bindings is still a key part of the development process. In this post I’ll run through some well known techniques for debugging bindings and touch on some changes that will impact debugging.

Binding basics

Before covering the debugging techniques, it’s worth stepping back and quickly running through how bindings work at a very basic level. For example, for the following simple example (available on JSBin if you want to follow along):

A stripped down binding implementation might look like the following:

Obviously, this code is a lot simpler than the real thing, and I’ve taken a couple of liberties, but it is still representative from a user’s perspective. The one big difference you’ll probably have spotted between it and the code you’re used to is the use of with statements, within which the bindings themselves are placed. Despite the negative perception of with statements, in this instance they’re incredibly useful. They allow bindings to reference the view model properties as if they were globals instead of prefixing everything with $data.x.

Syntax errors

You can probably already spot a common source of binding problems, if the binding contains a syntax error such that adding the curly braces doesn’t result in a valid JavaScript expression, Knockout will throw a binding error. For example, in 2.3.0, if instead of a colon we accidentally inserted a semi-colon between the key and the value, we’d get the following error when binding:

As I’ve hinted previously, the parsing process has never been quite that simple. Knockout 3.0 adopts an even more complex approach that allows for enhanced binding syntaxes (such as the text filters provided by knockout.punches. All valid bindings should obviously continue to work without issues, and in most cases syntax typos will still generate similar errors.

Unfortunately, and surprisingly to me for certain classes of typos such as the one above, it may no longer trigger a binding error and instead silently fail. I’m afraid there’s not much you can do to mitigate this one other than to be aware of it.

Reference errors

Another common source of binding errors is mistyping the name of an observable property. It’s easy to see how this would cause problems, even with the naive approach to binding above – trying to reference an undefined variable is going to cause a ReferenceError:

Knockout 3.0 makes it easier to distinguish typos in property names versus syntax errors. Internally once parsing is complete, each binding value is wrapped in an accessor function (function (){return ... }), and it’s that accessor function that you’ll see in the error. You’ll now see the following error instead:

Debugging tips

Knockout provides two utility methods that are very useful for debugging: ko.contextFor and ko.dataFor. Unsurprisingly, contextFor returns the context ($context) used when processing the bindings for a particular element, and dataFor returns the data ($data). I find these methods work best in combination with a less well-known feature of the developer tools bundled with browsers.

Once you’ve clicked on an element in the Elements view of the Chrome developer tools, it can then be referenced as $0 in the console. You can then type ko.contextFor($0), for instance, in the console to retrieve the context for the element.

These methods can be very useful for seeing what’s available in the scope of the bindings. For example, I find it quite easy to get lost in the stack if the view model has multiple levels of nesting.

Another tip is to use the debug version of Knockout, which adds an additional property to each observable called _latestValue, which as you might have guessed contains the latest value!

One final trick I discovered while combing through the dark-depths of binding, is to request the object representing all of the binding accessor functions. This is similar to the plain ko.contextFor($0) example, but instead of a pretty useless function observable() {, you instead get back the processed binding values wrapped in the accessor functions I described above, for example:

Conclusion

Debugging Knockout bindings can be a painful experience, especially if it all feels like black magic. Hopefully in this post I’ve revealed some of the secrets behind the bindings, and introduced you to a new technique or two for debugging them in the future.

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: debugging, Debugging tips, Javascript, JSBin, Knockout, Knockout 3.0, Knockout.js, MVVM,

Comments are closed.