DesirePRG
DesirePRG

Reputation: 6378

what does $data and $root mean in the following context

I am following the tutorials at knockoutjs website. This is a code from that.

view

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

viewmodel

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

ko.applyBindings(new WebmailViewModel());

what is $data and $root? where are they defined (where do they come from)?

Upvotes: 5

Views: 1397

Answers (1)

haim770
haim770

Reputation: 49095

When you're using a foreach binding, the binding-scope inside that block is the actual item you're iterating on. But sometimes you need to 'escape' that scope and get a reference to some property / method that is outside that scope.

  • Use $root to access the root view-model
  • Use $parent to access the object that is parent to the current scope

Also, you need to use $data to refer to the current item in the foreach loop. For example:

var vm = {
    arr: [1,2,3,4,5,6]
};

<div data-bind="foreach: arr">
    <span data-bind="text: $data"></span>
</div>

See Documentation

Upvotes: 5

Related Questions