knockout.js - 从DOM元素获取ViewModel

时间:2022-12-03 12:58:30

is is possible to get the binded ViewModel JavaScript object from a given DOM element?

是否可以从给定的DOM元素中获取绑定的ViewModel JavaScript对象?

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

Thanks in advance!

提前致谢!

1 个解决方案

#1


120  

Knockout has two utility methods that might help here.

Knockout有两种可能有用的实用方法。

  • ko.dataFor will return the ViewModel that the element is bound to.
  • ko.dataFor将返回元素绑定的ViewModel。
  • ko.contextFor returns the "binding context" of the current element. The object you get back from this method will return something like:

    ko.contextFor返回当前元素的“绑定上下文”。从此方法返回的对象将返回如下内容:

    { 
        $data: ...,
        $parents,
        $root
    }
    

So if I understand your question, you can probably use ko.dataFor here. Here's a simple example using dataFor.

所以,如果我理解你的问题,你可以在这里使用ko.dataFor。这是一个使用dataFor的简单示例。

#1


120  

Knockout has two utility methods that might help here.

Knockout有两种可能有用的实用方法。

  • ko.dataFor will return the ViewModel that the element is bound to.
  • ko.dataFor将返回元素绑定的ViewModel。
  • ko.contextFor returns the "binding context" of the current element. The object you get back from this method will return something like:

    ko.contextFor返回当前元素的“绑定上下文”。从此方法返回的对象将返回如下内容:

    { 
        $data: ...,
        $parents,
        $root
    }
    

So if I understand your question, you can probably use ko.dataFor here. Here's a simple example using dataFor.

所以,如果我理解你的问题,你可以在这里使用ko.dataFor。这是一个使用dataFor的简单示例。