Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  185] [ 5]  / answers: 1 / hits: 24088  / 11 Years ago, sat, march 9, 2013, 12:00:00

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?


More From » knockout.js

 Answers
89

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


[#79713] Friday, March 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;