KnockoutJS中变量$data的由来和用途是什么? [英] What is the origin and purpose of the variable $data in KnockoutJS?
问题描述
在 KnockoutJS 教程中,我偶然发现了以下代码示例,其中包含无法解释的变量 $data
.
In the KnockoutJS tutorials I stumbled upon the following code example that contains an unexplainable variable $data
.
视图(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):
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);
本教程不包含任何解释该美元符号的用途以及此 $data
的来源.变量 $data
未定义,当我将 $data
的所有三个实例重命名为 $foobar
时,该示例不再起作用.
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?
推荐答案
$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 the viewModel.folders
array.
这篇关于KnockoutJS中变量$data的由来和用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!