在浏览器中运行时,在其中一种Knockout视图模型中更改数据的最简单方法是什么? [英] What is the easiest way to change data in one of the Knockout viewmodels while running in the browser?
问题描述
我正在运行(我自己构建的)KnockOut.JS应用程序. 在其中一个视图模型中更改数据的最简单方法是什么?
I am running (my own built) KnockOut.JS application. What is the easiest way to CHANGE data in one of the viewmodels?
我没有可以在控制台中更改的全局JS对象,并且我有多个具有各自绑定的元素. 我当然可以在viewmodel上创建一个按钮和一个方法,但是我想在Viewmodel上玩一些值以查看UI中的效果.
I do not have a global JS object I can change in the console, and I have multiple elements with their own binding. I can of course create a button and a method on the viewmodel, but I want to play around with some values on the viewmodel to see the effect in the UI.
最好在Chrome浏览器中.
Preferably in Chrome.
推荐答案
在开发淘汰型网站/应用程序时,您通常希望使用不同的值来查看UI的反应.
When developing a knockout website/application you often want to play around with different values to see how your UI reacts.
当您自己的代码被整齐地包含且无法通过window
访问时,可能很难获得对视图模型的访问.
When your own code is neatly contained and not accessible via window
, it can be difficult to gain access to your viewmodels.
当然,您可以修改代码以在窗口中显示某些属性(例如:window.myObsProp = this.myObsProp
).但是,这需要您编辑代码,并且在使用视图模型列表时可能会很烦人.
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.
因此,一种快速的替代方法是使用敲除的dataFor
和contextFor
实用程序功能. 1
Therefore, a quick alternative is to use knockout's dataFor
and contextFor
utility functions.1
使用ko.dataFor
或ko.contextFor
,您可以返回DOM特定部分的绑定上下文. ko.dataFor(element)
是ko.contextFor(element).$data
的简写.
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
.
要快速访问元素,大多数浏览器会公开一个$0
全局变量,该变量包含最后检查的元素.因此,您可以使用以下方法检索视图模型:
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")
- get:
vm.myObsProp()
- set:
vm.myObsProp("some new value")
关于淘汰赛的你好世界示例
1. 这确实要求您在全局范围(window
)中公开ko
.
这篇关于在浏览器中运行时,在其中一种Knockout视图模型中更改数据的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!