我在调试KnockoutJS模板中的问题时一直遇到麻烦。

假设我想绑定到一个名为“items”的属性,但在模板中我犯了一个错字,并绑定到(不存在的)属性“item”。

使用Chrome调试器只告诉我:

“item”没有定义。

是否有工具、技术或编码风格可以帮助我获得关于绑定问题的更多信息?


当前回答

如果您使用Chrome进行开发,有一个非常棒的扩展(我没有加入)称为Knockoutjs上下文调试器,它直接在开发人员工具的元素面板中向您显示绑定上下文。

其他回答

循序渐进指南

For this guide, we will be using one of the official KnockoutJS examples. Say you want to see the data behind the second contact (Sensei Miyagi). Right-click the first input box of the second contact (the one with the text 'Sensei'). Select 'Inspect element'. The Chrome Developer Toolbar will open. Open the JavaScript Console window. You can access the console by clicking the >= icon in the bottom-left of the Chrome Developer Toolbar, or by opening the "Console" tab in the Chrome Developer Toolbar, or by pressing Ctrl+Shift+J Type the following command and press Enter: ko.dataFor($0) You should now see the data that is bound to the second row. You can expand the data by pressing the little triangle left of the Object to navigate the object tree. Type the following command and press Enter: ko.contextFor($0) You should now see a complex object that contains the entire Knockout context including the root and all parents. This is useful when you are writing complex binding expressions and you want to experiment with different constructs.

这是什么黑魔法?

这个技巧是Chrome的$0-$4功能和KnockoutJS的实用程序方法的组合。简而言之,Chrome会记住你在Chrome开发工具栏中选择了哪些元素,并以别名$0,$1,$2,$3,$4公开这些元素。因此,当你在浏览器中右键单击一个元素并选择“Inspect element”时,这个元素自动以别名$0变为可用。你可以在KnockoutJS, AngularJS, jQuery或任何其他JavaScript框架中使用这个技巧。

诀窍的另一方面是KnockoutJS的实用程序方法ko。dataFor和ko.contextFor:

ko.dataFor(element)——返回可用于绑定的数据 与大自然对抗 ko.contextFor(element) -返回被绑定的整个绑定上下文 DOM元素可用。

记住,Chrome的JavaScript控制台是一个功能齐全的JavaScript运行时环境。这意味着您不仅仅局限于查看变量。您可以存储ko的输出。contextFor和直接从控制台操作视图模型。试试var root = ko.contextFor($0).$root;root.addContact ();看看会发生什么:-)

调试快乐!

我创建了一个名为knock - through.js的github项目来帮助可视化这些错误。

https://github.com/JonKragh/knockthrough

它突出显示绑定错误,并提供该节点上的数据上下文的转储。

你可以在这里玩一个例子:http://htmlpreview.github.io/?https://github.com/JonKragh/knockthrough/blob/master/default.htm

感谢RP Niemeyer,他在SO上出色的Knockout代码示例让我走到这一步。

如果你在Magento项目中使用KnockoutJS,你可以使用Magento的自定义afterRender绑定:

<div afterRender="function (target, viewModel) {
    console.log('Rendered element:', target);
    console.log('Associated view model:', viewModel);
    console.log(this === viewModel);
}"></div> 

所有其他的答案都很好,我只是添加了我喜欢做的事情:

在你的视图中(假设你已经绑定了一个ViewModel):

<div data-bind="debugger: $data"></div>

淘汰赛代码:

ko.bindingHandlers.debugger = {
    init: function (element, valueAccessor) {
        debugger;
    }
}

这将暂停调试器中的代码,element和valueAccessor()将包含有价值的信息。

如果您使用Chrome进行开发,有一个非常棒的扩展(我没有加入)称为Knockoutjs上下文调试器,它直接在开发人员工具的元素面板中向您显示绑定上下文。