Javascript Knockout.js - 从 DOM 元素获取 ViewModel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14015497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
knockout.js - Get ViewModel from DOM element
提问by Dirk Boer
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 );
回答by Andrew Whitaker
Knockout has two utility methodsthat might help here.
Knockout 有两种实用方法可能会有所帮助。
ko.dataForwill return the ViewModel that the element is bound to.ko.contextForreturns the "binding context" of the current element. The object you get back from this method will return something like:{ $data: ..., $parents, $root }
ko.dataFor将返回元素绑定到的 ViewModel。ko.contextFor返回当前元素的“绑定上下文”。您从此方法返回的对象将返回如下内容:{ $data: ..., $parents, $root }
So if I understand your question, you can probably use ko.dataForhere. Here's a simple exampleusing dataFor.
所以如果我理解你的问题,你可能可以ko.dataFor在这里使用。这是一个使用dataFor.

