Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 284
DesirePRG Avatar asked May 07 '15 06:05

DesirePRG


1 Answers

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

like image 135
haim770 Avatar answered Sep 30 '22 07:09

haim770