檢查 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