Knockout.js syntax

♀尐吖头ヾ 提交于 2019-12-12 09:08:07

问题


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

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

Consider the statments below;

The View:

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

View Model:

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

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

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


回答1:


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.

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) 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.

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()
});

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

Thanks Tjorriemorrie ;-)




回答2:


Answering your question about self.chosenFolderId(folder)

It writes value to chosenFolderId observable. The value of argument "folder" is actually current value of $data.




回答3:


If you try to change reference from self to this ( which is the same thing) in the provided code , then the selection css doesn't work. Does anybody know why ?

this.goToFolder = function(folder) { this.chosenFolderId(folder); };   



回答4:


Regarding your question:

what the statements do (specifically $data, $root) ?

$data: represents the current viewmodel. It's useful inside foreach loops. eg- if we have collection of students and we are iterating this collection, $data give us the current student instance. So that we can use $data to get the various properties of the student object like name, class, etc

$root: This is the root viewmodel, the highest context in the hierarchy. So through $root, you can get access to the top level properties.



来源:https://stackoverflow.com/questions/9632767/knockout-js-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!