Solving Knockout JS calculated bindings Syntax Error

Solving Knockout JS calculated bindings Syntax Error

Knockout JS does an excellent job in binding the interface with a View Model. Sometimes you'll need some data manipulation before a value can be shown to the users. How would you go about?

A few options come to mind:

Using more complex operations might result in the JavaScript exception: Uncaught SyntaxError: Unable to parse bindings.

Printing the position

Let's say we need to list the position of an object in an observable array, with the following rules:

First try: wrong way

When I tried to implement this, I used the following - but it did not work:

<span data-bind="text: { 
    var x = $index; 
    x += 1; 
    if(x < 10) x = '0' + x; 
    return x + '.'; 
} "></span>

KnockoutJS doesn't know how to parse this and you'll end up with an error.

Anonymous function to the rescue

The trick is to wrap it into an anonymous function and calling it with the index as a parameter. Because of the nature of this function, we must evaluate the observables that are passed (use () to get the value).

<span data-bind="text: 
    (function(i) { 
        i += 1; 
        if(i < 10) i = '0' + i; 
        return i + '.'; 
    })($index());
">
</span>

This technique is frequently used in JavaScript to achieve information hiding.