检查 DOM 元素的绑定上下文

敲除数据绑定中的许多错误都是由视图模型中的未定义属性引起的。Knockout 有两个方便的方法来检索 HTML 元素的绑定上下文

// Returns the binding context to which an HTMLElement is bound
ko.contextFor(element);    

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

要快速找到 UI 元素的绑定上下文,这里有一个方便的技巧:

大多数现代浏览器将当前选定的 DOM 元素存储在全局变量中:$0更多关于此机制

  • 右键单击 UI 中的元素,然后在上下文菜单中选择 inspectinspect element
  • 在开发者控制台中键入 ko.dataFor($0),然后按 Enter 键

还存在浏览器插件,其可以帮助查找对象上下文。

一个例子(在 Knockout hello world 示例中尝试 ):

http://i.stack.imgur.com/dHP6G.gif