javascript 为什么这里需要 $root?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10797728/
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
Why is $root required here?
提问by Tim Tom
I am just referring the tutorials from knockout.js:
我只是参考knockout.js 的教程:
http://learn.knockoutjs.com/#/?tutorial=webmail
http://learn.knockoutjs.com/#/?tutorial=webmail
In the UI the markup is:
在 UI 中,标记是:
<!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data,
css: { selected: $data == $root.chosenFolderId() },
click: $root.goToFolder"></li>
</ul>
and it's ViewModel is:
它的 ViewModel 是:
function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
// Behaviours
self.goToFolder = function(folder) { self.chosenFolderId(folder); };
};
ko.applyBindings(new WebmailViewModel());
Can anybody tell me what is is $root and why is it required? If I remove it, it doesn't work.
谁能告诉我什么是 $root 以及为什么需要它?如果我删除它,它不起作用。
回答by freakish
$root
refers to the top model in KnockoutJS hierarchy (the one you use in .applyBindings
). In your case WebmailViewModel
object is the $root
.
$root
指的是 KnockoutJS 层次结构中的顶级模型(您在 中使用的模型.applyBindings
)。在您的情况下,WebmailViewModel
对象是$root
.
It is required, because when you use foreach
then inside the loop the context changes. Everything you want to fire here is associated to an element within a loop. Thus you need $root
to use functions/fields defined outside of that context (in your case chosenFolderId
is a method of WebmailViewModel
object).
这是必需的,因为当您foreach
在循环内使用then时,上下文会发生变化。您想在此处触发的所有内容都与循环中的元素相关联。因此,您需要$root
使用在该上下文之外定义的函数/字段(在您的情况下chosenFolderId
是WebmailViewModel
对象的方法)。
回答by Jim Schubert
You'll need to check out the binding contextspage.
您需要查看绑定上下文页面。
$root
This is the main view model object in the root context, i.e., the topmost parent context. It is equivalent to $parents[$parents.length - 1].
$root
这是根上下文中的主要视图模型对象,即最顶层的父上下文。它相当于$parents[$parents.length - 1]。
回答by Vikas Verma
The $root
context always refers to the top-level ViewModel, regardless of loops or other changes in scope. This allow us to access top-level methods for manipulating the ViewModel.
所述$root
上下文总是指顶层视图模型,而不管环路或在范围其他变化。这允许我们访问用于操作 ViewModel 的顶级方法。
In your example $data
represent to folder array values like 'Inbox', 'Archive','Sent' and 'spam'. But $root
represent root functions of ViewModel like chosenFolderId
and goToFolder
.
在您的示例中,$data
代表文件夹数组值,如“收件箱”、“存档”、“已发送”和“垃圾邮件”。但是$root
代表 ViewModel 的根函数,如chosenFolderId
和goToFolder
。
I think this link examples will help you more.
我认为这个链接示例会帮助你更多。