Using Chrome Console to Access Knockout ViewModel with RequireJS

后端 未结 3 1372
长情又很酷
长情又很酷 2021-01-31 05:07

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 ev

3条回答
  •  [愿得一人]
    2021-01-31 05:27

    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

提交回复
热议问题