I am just referring the tutorials from knockout.js:
http://learn.knockoutjs.com/#/?tutorial=webmail
In the UI the markup is:
<!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data,
css: { selected: $data == $root.chosenFolderId() },
click: $root.goToFolder"></li>
</ul>
and it's ViewModel is:
function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
// Behaviours
self.goToFolder = function(folder) { self.chosenFolderId(folder); };
};
ko.applyBindings(new WebmailViewModel());
Can anybody tell me what is is $root and why is it required? If I remove it, it doesn't work.
$root
refers to the top model in KnockoutJS hierarchy (the one you use in .applyBindings
). In your case WebmailViewModel
object is the $root
.
It is required, because when you use foreach
then inside the loop the context changes. Everything you want to fire here is associated to an element within a loop. Thus you need $root
to use functions/fields defined outside of that context (in your case chosenFolderId
is a method of WebmailViewModel
object).
You'll need to check out the binding contexts page.
$root
This is the main view model object in the root context, i.e., the topmost parent context. It is equivalent to $parents[$parents.length - 1].
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