KnockoutJS 中变量 $data 的起源和用途是什么?
在KnockoutJS教程中,我偶然发现了以下代码示例,其中包含无法解释的变量$数据
。
视图 (html):
<!-- Folders -->
<ul class="folders" data-bind="template: { name: 'folderTemplate', foreach: folders }"></ul>
<script type="text/html" id="folderTemplate">
<li data-bind="css: { selected: $data == mailViewModel.selectedFolder() },
click: function() { mailViewModel.selectFolder($data) }">
${$data}
</li>
</script>
视图模型 (JavaScript):
var viewModel = {
// Data
folders: ['Inbox', 'Archive', 'Sent', 'Spam'],
selectedFolder: ko.observable('Inbox'),
// Behaviours
selectFolder: function (folder) {
this.selectedFolder(folder);
}
};
window.mailViewModel = viewModel;
ko.applyBindings(viewModel);
本教程不包含任何说明美元符号的用途以及此 $data
的来源。变量 $data
没有定义,当我将 $data
的所有三个实例重命名为 $foobar
时,该示例不再起作用。
这里到底发生了什么魔法?
In the KnockoutJS tutorials I stumbled upon the following code example that contains an unexplainable variable $data
.
The View (html):
<!-- Folders -->
<ul class="folders" data-bind="template: { name: 'folderTemplate', foreach: folders }"></ul>
<script type="text/html" id="folderTemplate">
<li data-bind="css: { selected: $data == mailViewModel.selectedFolder() },
click: function() { mailViewModel.selectFolder($data) }">
${$data}
</li>
</script>
The View Model (JavaScript):
var viewModel = {
// Data
folders: ['Inbox', 'Archive', 'Sent', 'Spam'],
selectedFolder: ko.observable('Inbox'),
// Behaviours
selectFolder: function (folder) {
this.selectedFolder(folder);
}
};
window.mailViewModel = viewModel;
ko.applyBindings(viewModel);
The tutorial does not contain any explanation what that dollar sign is used for and where this $data
comes from. The variable $data
is nowhere defined and when I rename all three instances of $data
to $foobar
, the example does not work anymore.
What kind of magic is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$data 是 Knockout 绑定上下文的一部分。
以下是所有内置变量:
$data is part of Knockout's Binding Contexts.
Here are all the built-in variables:
$data
变量是一个内置变量,用于引用当前绑定的对象。在示例中,这是 viewModel.folders 数组中的元素之一。The
$data
variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in theviewModel.folders
array.我成功了,
请看一下
http://jsfiddle.net/bowen31337/48RDd/
i made it work
please take a look at
http://jsfiddle.net/bowen31337/48RDd/