I keep having trouble with debugging problems in KnockoutJS templates.
Say I want to bind to a property called "items
" but in the template I make a typo and bind to the (non existing) property "item
".
Using the Chrome debugger only tells me:
"item" is not defined.
Are there tools, techniques or coding styles that help me get more information about the binding problem?
If you are developing in Visual studio and IE I like this more
data-bind="somebinding:(function(){debugger; return bindvalue; })()"
I like it more then echo function since it will go to the script with all the bindings rather the the eval file and you can just look at the $context $data(I use this in Chrome as well);One thing that I do quite often when there is an issue with what data is available at a certain scope is to replace the template/section with something like:
Or, if you want a slightly more readable version:
This will spit out the data that is being bound at that scope and let you make sure that you are nesting things appropriately.
Update: as of KO 2.1, you can simplify it to:
Now the arguments are passed on to
JSON.stringify
.I found another one that can be helpfull. I was debugging some bindings and tried using Ryans example. I got an error that JSON found a circular loop.
But, using this approach a replaced the data-bind value with the following:
Now if i click on the PRE element while having the chrome debug window open, I get a nicely filled scope variables window.
Found a little better way for it:
Check out a really simple thing I use:
Or
Then in html, say, you had:
Just replace it with
More advanced:
Enjoy :)
UPDATE
Another annoying thing is when you are trying to bind to an undefined value. Imagine in the example above that the data object is just {} not { value: 'some text' }. In this case you will be in trouble, but with the following tweak you will be fine:
Define a bindingHandler once, somewhere in your JavaScript library files.
than simply use it likes this:
Advantages
The easiest way to see what data are passed to binding is to drop the data to console:
Knockout will evaluate value for text binding (any binding can be used here in fact) and flushes $data to console browser panel.