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
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:
var vm = ko.dataFor($0)
To retrieve properties and edit them:
vm.myObsProp()
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
).