在浏览器中运行时更改 Knockout 视图模型之一中的数据的最简单方法是什么? [英] What is the easiest way to change data in one of the Knockout viewmodels while running in the browser?

查看:23
本文介绍了在浏览器中运行时更改 Knockout 视图模型之一中的数据的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行(我自己构建的)KnockOut.JS 应用程序.在其中一个视图模型中更改数据的最简单方法是什么?

我没有可以在控制台中更改的全局 JS 对象,而且我有多个具有自己绑定的元素.我当然可以在 viewmodel 上创建一个按钮和一个方法,但我想在 viewmodel 上使用一些值来查看 UI 中的效果.

最好在 Chrome 中.

解决方案

在开发淘汰网站/应用程序时,您经常想尝试使用不同的值来查看 UI 的反应.

当您自己的代码被整齐地包含并且无法通过 window 访问时,可能很难访问您的视图模型.

当然,您可以修改代码以在窗口中公开某些属性(例如:window.myObsProp = this.myObsProp).但是,这需要您编辑代码,并且在处理视图模型列表时可能会很烦人.

因此,一个快速的替代方法是使用knockout 的dataForcontextFor 实用函数.1

使用 ko.dataForko.contextFor 您可以返回 DOM 特定部分的绑定上下文.ko.dataFor(element)ko.contextFor(element).$data 的简写.

为了快速访问元素,大多数浏览器公开了一个 $0 全局变量,其中包含最后检查的元素.因此,您可以使用以下方法检索您的视图模型:

  1. 鼠标右键 -> 检查元素
  2. 在控制台:var vm = ko.dataFor($0)

要检索属性并对其进行

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

关于淘汰赛的

1.这确实需要您在全局范围(window)中公开ko.

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 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.

Preferably in Chrome.

解决方案

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).

这篇关于在浏览器中运行时更改 Knockout 视图模型之一中的数据的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆