Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $root required here?

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.

like image 261
Tim Tom Avatar asked May 29 '12 10:05

Tim Tom


2 Answers

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

like image 184
freakish Avatar answered Sep 28 '22 16:09

freakish


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

like image 21
Jim Schubert Avatar answered Sep 28 '22 16:09

Jim Schubert