knockout.js - 从DOM元素获取ViewModel [英] knockout.js - Get ViewModel from DOM element
问题描述
是否可以从给定的DOM元素中获取绑定的ViewModel JavaScript对象?
is is possible to get the binded ViewModel JavaScript object from a given DOM element?
ko.applyBindings( gLoginViewModel, document.getElementById("login-form") );
ko.applyBindings( gLoginViewModel, document.getElementById("register-form") );
以及其他地方 - 相当不相关的代码 - 类似这样:
and somewhere else - in rather unrelated code - something like this:
var viewModel = ko.getViewModel( formElement );
viewModel.someObservable( someData ); // observable available in all ViewModels
如果我可以做的话会更好:
it would even be better if I could do something like:
var viewModel = ko.getViewModel( someChildElement );
提前致谢!
推荐答案
Knockout有两个实用程序方法,可能对此有所帮助。
Knockout has two utility methods that might help here.
-
ko.dataFor
将返回元素绑定的ViewModel。 -
ko.contextFor
返回当前元素的绑定上下文。您从此方法返回的对象将返回如下内容:
ko.dataFor
will return the ViewModel that the element is bound to.ko.contextFor
returns the "binding context" of the current element. The object you get back from this method will return something like:
{
$data: ...,
$parents,
$root
}
因此,如果我理解你的问题,你可以在这里使用 ko.dataFor
。使用 dataFor
这是一个简单的示例。
So if I understand your question, you can probably use ko.dataFor
here. Here's a simple example using dataFor
.
这篇关于knockout.js - 从DOM元素获取ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!