使用 Chrome 控制台通过 RequireJS 访问 Knockout ViewModel [英] Using Chrome Console to Access Knockout ViewModel with RequireJS
问题描述
既然我正在使用 RequireJS,如何在 Chrome 控制台中访问 KnockOut ViewModel 变量?
How do I access the KnockOut ViewModel variables in the Chrome console now that I am using RequireJS?
在使用 RequireJS 之前,我遵循命名空间模式,将所有内容隐藏在一个全局中.我可以通过在 Chrome 控制台中输入以下内容来访问全局:window.namespaceVar.
Before using RequireJS, I followed a namespacing pattern, hiding everything within a single global. I could access the global by typing the following into the Chrome console: window.namespaceVar.
但是现在我使用 RequireJS,我所有的变量都隐藏在 require 函数后面.
But now that I am using RequireJS, all my variables are hidden behind the require function.
require(['knockout-2.2.0', 'jquery'], function (ko, jQuery) {
var ViewModel = function () {
var testVar = ko.observable(true);
};
ko.applyBindings(new ViewModel());
}
那么我将如何访问示例中 testVar
的当前值?
So how would I access the current value of testVar
in the example?
推荐答案
Knockout 包括函数 ko.dataFor
和 ko.contextFor
,它们将使您能够访问 KO查看给定元素的模型信息.
Knockout includes the functions ko.dataFor
and ko.contextFor
that will give you access to the KO view model information given an element.
因此,在控制台中,您可以执行以下操作:
So, in the console, you can do something like:
var vm = ko.dataFor(document.body);
在您的情况下,testVar
未公开,因此您仍然无法访问它.我认为你的只是一个样本,你的意思是:
In your case, testVar
is not exposed, so you would still not be able to access it. I assume that yours was just a sample though and you meant something like:
var ViewModel = function () {
this.testVar = ko.observable(true);
};
现在,使用上述方法,您可以通过执行 vm.testVar()
Now, using the above method you would be able to access vm.testVar
and its value by doing vm.testVar()
以下是我们关于这些函数的文档:http://knockoutjs.com/documentation/unobtrusive-event-handling.html
Here are the docs that we have on these functions: http://knockoutjs.com/documentation/unobtrusive-event-handling.html
这里有一个关于如何使用 chrome 调试 KnockoutJS 的分步指南:http://devillers.nl/quick-debugging-knockoutjs-in-chrome/一个>
and here's a step-by-guide on how to debug KnockoutJS with chrome: http://devillers.nl/quick-debugging-knockoutjs-in-chrome/
使用 Chrome 的 $0_$4 功能:https://developers.google.com/chrome-developer-tools/docs/commandline-api#0-4
using Chrome's $0_$4 feature: https://developers.google.com/chrome-developer-tools/docs/commandline-api#0-4
这篇关于使用 Chrome 控制台通过 RequireJS 访问 Knockout ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!