knockout.js Checking the binding context of a DOM element


Many bugs in knockout data binds are caused by undefined properties in a viewmodel. Knockout has two handy methods to retrieve the binding context of an HTML element:

// Returns the binding context to which an HTMLElement is bound

// Returns the viewmodel to which an HTMLElement is bound
// similar to: ko.contextFor(element).$data

To quickly find out the binding context of a UI element, here's a handy trick:

Most modern browsers store the currently selected DOM element in a global variable: $0 (more about this mechanism)

  • Right click an element in your UI and choose "inspect" or "inspect element" in the context menu.
  • type ko.dataFor($0) in the developer console and press enter

Browser plugins also exist which may assist with finding the object context.

An example (try it on Knockout hello world example):

A gif showing how to quickly log knockout's binding context for a UI element