What is the easiest way to change data in one of the Knockout viewmodels while running in the browser?

前端 未结 2 833
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 00:25

I am running (my own built) KnockOut.JS application. What is the easiest way to CHANGE data in one of the viewmodels?

I do not have a global JS object I can change i

2条回答
  •  既然无缘
    2020-12-07 00:36

    When developing a knockout website/application you often want to play around with different values to see how your UI reacts.

    When your own code is neatly contained and not accessible via window, it can be difficult to gain access to your viewmodels.

    Of course, you can modify your code to expose certain properties in window (e.g.: window.myObsProp = this.myObsProp). However, this requires you to edit your code and can be quite annoying when working with lists of viewmodels.

    Therefore, a quick alternative is to use knockout's dataFor and contextFor utility functions.1

    Using ko.dataFor or ko.contextFor you can return the binding context for a specific part of the DOM. ko.dataFor(element) is a shorthand for ko.contextFor(element).$data.

    To quickly gain access to an element, most browsers expose a $0 global variable that contains the last inspected element. You can therefore retrieve your viewmodel using:

    1. Right mouse button -> inspect element
    2. In console: var vm = ko.dataFor($0)

    To retrieve properties and edit them:

    1. get: vm.myObsProp()
    2. set: vm.myObsProp("some new value")

    An example on knockout's hello world example

    1. This does require you to expose ko in the global scope (window).

提交回复
热议问题