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)?
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.
$root
to access the root view-model$parent
to access the object that is parent to the current scopeAlso, 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
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