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:

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

<th>Product models</th>
<th>List Price</th>
<!-- ko if: $root.debug -->
<!-- /ko -->

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

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