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 ?
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With