knockout.js Printing a binding context from markup


Example

Sometimes it is useful to print a current binding directly from markup. A neat trick which allows that is to use an additional DOM element with a non-existing binding (KO < 3.0), custom binding or a binding that is not relevant such as uniqueName.

Consider this example:

<tbody data-bind="foreach: people">
    <tr>
         <td data-bind="text: firstName"></td>
         <td data-bind="text: lastName"></td>
    </tr>
</tbody>

If one would like to to find out the binding context of each element in the people array, one can write:

<tbody data-bind="foreach: people">
    <span data-bind="uniqueName: console.log($data)"></span>
    <tr>
        <td data-bind="text: firstName"></td>
        <td data-bind="text: lastName"></td>
    </tr>
</tbody>