Using Chrome Console to Access Knockout ViewModel with RequireJS

十年热恋 提交于 2019-12-03 03:44:58

问题


How do I access the KnockOut ViewModel variables in the Chrome console now that I am using RequireJS?

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.

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());
}

So how would I access the current value of testVar in the example?


回答1:


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);

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);
};

Now, using the above method you would be able to access vm.testVar and its value by doing vm.testVar()

Here are the docs that we have on these functions: http://knockoutjs.com/documentation/unobtrusive-event-handling.html

and here's a step-by-guide on how to debug KnockoutJS with chrome: http://devillers.nl/quick-debugging-knockoutjs-in-chrome/

using Chrome's $0_$4 feature: https://developers.google.com/chrome-developer-tools/docs/commandline-api#0-4




回答2:


As Ryan suggested, the quickest way is to use ko.contextFor and ko.dataFor in the console to see the binding context of an element on the dom.

There's also a very useful Chrome Extension that uses this principle called KnockoutJS Context Debugger, available here:

Chrome Web Store - KnockoutJS Context Debugger

It allows you to inspect an element and see it's context in the sidebar of the elements pane. It's most useful it you have multiple binding contexts on a page, or very nested binding contexts.




回答3:


Require is all about not having globals:

require(["knockout"],function(ko){ window.ko=ko;}); 

is introducing globals again

You can use this in the console:

require("knockout").dataFor($0);
require("knockout").contextFor($0);


来源:https://stackoverflow.com/questions/15310659/using-chrome-console-to-access-knockout-viewmodel-with-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!