In the KnockoutJS tutorials I stumbled upon the following code example that contains an unexplainable variable $data
.
The View (html):
<!-- Folders --> <ul class="folders" data-bind="template: { name: 'folderTemplate', foreach: folders }"></ul> <script type="text/html" id="folderTemplate"> <li data-bind="css: { selected: $data == mailViewModel.selectedFolder() }, click: function() { mailViewModel.selectFolder($data) }"> ${$data} </li> </script>
The View Model (JavaScript):
var viewModel = { // Data folders: ['Inbox', 'Archive', 'Sent', 'Spam'], selectedFolder: ko.observable('Inbox'), // Behaviours selectFolder: function (folder) { this.selectedFolder(folder); } }; window.mailViewModel = viewModel; ko.applyBindings(viewModel);
The tutorial does not contain any explanation what that dollar sign is used for and where this $data
comes from. The variable $data
is nowhere defined and when I rename all three instances of $data
to $foobar
, the example does not work anymore.
What kind of magic is going on here?
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).
To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
$data is part of Knockout's Binding Contexts.
Here are all the built-in variables:
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