Knockout.js语法 [英] Knockout.js syntax

查看:77
本文介绍了Knockout.js语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Javascript MVC框架Knockout.js的初学者

I am a beginner to the Javascript MVC framework Knockout.js

基于常规Javascript(和一些jQuery经验),我在理解语法学习Knockout.js方面遇到困难

Coming from conventional Javascript (and some jQuery experience), I am having difficulties in understanding the syntax learning Knockout.js

考虑以下陈述;

视图:

<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data, 
               css: { selected: $data == $root.chosenFolderId() },
               click: $root.goToFolder"></li></ul>

查看模型:

function WebmailViewModel() {
    // Data
    var self = this;
    self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
    self.chosenFolderId = ko.observable();

    // Behaviours    
    self.goToFolder = function(folder) { self.chosenFolderId(folder); };    
};

您能否解释一下这些语句的作用(特别是$ data,$ root)? 语句self.chosenFolderId(folder);的作用是什么?

Could you please explain me what the statements do (specifically $data, $root) ? Also what does the statement self.chosenFolderId(folder); does ?

推荐答案

KO通常使用$ data和$ root关键字. 当您在数组上使用foreach时(数据绑定),KO为数组中的每个元素创建一个<li>.

The $data and $root keywords are typically used by KO. When you use the foreach on array ( data-bind), KO creates one <li> for each element in the array.

在这种情况下,$ data是数组的当前项(如folders [i]),而$ root是父元素. 对您来说,文件夹是ViewModel的一个字段: $ data =迭代中的当前文件夹(viewModel.folder [i]) $ root = viewModel

In this case, $data is the current item of array (like folders[i]) and $root is the parent element. For you, folders is a field of your ViewModel : $data = current folders on the iteration (viewModel.folder[i]) $root = viewModel

self.chosendFolderId(folder)执行viewModel selectedFolderId方法.该代码使用self保留viewModel的值,因为在函数中关键字"this"不是viewModel而是方法的发送者.这是一个关闭.

self.chosendFolderId(folder) execute you viewModel chosenFolderId method. The code use self to keep the viewModel value because in the function the keyword "this" isn't the viewModel but the method's sender. It's a closure.

$ parent关键字是树的上一级. $ root关键字是顶层树的级别.

Edit : The $parent key word is the tree's previus level. The $root key word is the top tree's level.

viewModel {
  topObjects : ko.observableArray()
}

viewModel.topObjects.push({
  Objects : ko.observableArray()
});

如果我们在viewModel.topObjects.Objects上创建foreach,则$ parent是topObjects,$ root是viewModel.

If we create a foreach on viewModel.topObjects.Objects, the $parent is topObjects, $root is viewModel.

感谢Tjorriemorrie;-)

Thanks Tjorriemorrie ;-)

这篇关于Knockout.js语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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