Knockout Debugging Sample
Notes
  • Let's get access to underlying Knockout data, called view model. Right click on number or buttons and select "Inspect Element".
  • Type following into console to get access to data vm = ko.dataFor($0)
  • Now, get currentNum in console using vm.currentNum(). The currentNum is an ko.observable, which means you have to call it with no arguments to get the current value. If you forget to add the parens, you will simply see the observable function definition not the current value.
  • Click buttons and then use up arrow to re-execute vm.currentNum() to see that is in fact the current value
  • Now, update the currentNum using vm.currentNum(100);. Check the value using vm.currentNum(). The value has updated and the UI has updated, the Increase button has been disabled. But there is a bug, the candy stripe wasn't updated.
  • Before we fix that, let's do some debugging to see if the page title is part of the Knockout view model.
  • Right-click to inspect the page title element and then type ko.dataFor($0). Notice that undefined is returned, meaning the page title is outside of Knockout and therefore isn't controlled by Knockout.
  • Back to the candy stripe bug, if you look at the source code, app.js, on line 28, 33 you'll see we call syncWithNumber after updating currentNum. This updates the data for the candy stripe. We didn't call that from the console, so try that now, vm.syncWithNumber();
  • Let's see if we can clean that code up by subscribing to currentNum and when it changes automatically calling syncWithNumber. So, let's try subscribing to currentNum, vm.currentNum.subscribe(function () { console.log('currentNum changed to ' + vm.currentNum()); });. Confirm the subscription works by clicking on the buttons and watching the console.
  • Now, we can add a subscription that calls syncWithNumber, vm.currentNum.subscribe(vm.syncWithNumber, vm);
  • Let's test updating currentNum and see if UI and candy stripe update, vm.currentNum(10);
  • So, now we could take our subscription that we tested and update our source code in app.js
  • But, let's try accessing a service. In this app we have a ColorService that when given a number will return a color. This is useful for unit testing and for allowing users to select between services to change the candy stripe. Let's see if we can interact with this service from the console.
  • Knockout is only concerned about the view layer, it provides no guidance or assistance for other parts of an application like Services. For this app, the Color Service is simply a JS global variable, app.ColorService.
  • Now, let's test the Color Service using app.ColorService.determine(5) and app.ColorService.determine(10);
  • And that's the end of debugging Knockout using the Console