KnockoutJS中变量$ data的来源和目的是什么? [英] What is the origin and purpose of the variable $data in KnockoutJS?

查看:102
本文介绍了KnockoutJS中变量$ data的来源和目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

KnockoutJS教程中,我偶然发现了下面的代码示例,其中包含无法解释的变量 $ data



视图(html):

<! - 文件夹 - >
< ul class =foldersdata-bind =template:{name:'folderTemplate',foreach:folders}>< / ul>
< script type =text / htmlid =folderTemplate>
< li data-bind =css:{selected:$ data == mailViewModel.selectedFolder()},
click:function(){mailViewModel.selectFolder($ data)}>
$ {$ data}
< / li>
< / script>

视图模型(JavaScript):

 var viewModel = {
//数据
文件夹:['收件箱','存档','发送','垃圾邮件'],
selectedFolder :ko.observable('Inbox'),

// Behaviors
selectFolder:function(folder){
this.selectedFolder(folder);
}
};

window.mailViewModel = viewModel;
ko.applyBindings(viewModel);

本教程不包含任何解释美元符号用于何处以及 $ data 来自。变量 $ data 没有定义,当我将 $ data 的所有三个实例重命名为 $ foobar ,该示例不再有效。



这是怎么回事? $ data 变量是一个内置变量,用于引用当前绑定的对象。在这个例子中,这是 viewModel.folders 数组中的元素之一。

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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆