Pages

Thursday, April 18, 2013

How to debug a content for knockout

One of the most boring thing a developer have to do is debugging and it’s very painful when there are thousand of JavaScript library on your page. And if you are an user of Knockoutjs you could have problem to binding the data on your View.

A good way to see your object on your page, to understand if the data is correct and what could be the error, is print the object is a piece of HTML.

So in deeply it is not hard to understand, following is a piece of my view:

<div>
Debug: <input type="checkbox" data-bind="checked: debug" /> <label data-bind="text: debugMsg"></label>
</div>

<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Product models</th>
<th>List Price</th>
<th>Qty</th>
<th></th>
<th></th>
<!-- ko if: $root.debug -->
<th></th>
<!-- /ko -->
</tr>
</thead>

<!-- ..... -->



<!-- ko if: $root.debug -->
<td>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</td>
<!-- /ko -->


 

The label is not useful but I keep it just for DEMO purpose. To bind this two variables you need something like this:

 

self.debug = ko.observable(false);
self.debugMsg = ko.computed(function () {
return self.debug() === true ? "We are in == DEBUG MODE ==" : "";
});


that’s it

No comments:

Post a Comment