Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the origin and purpose of the variable $data in KnockoutJS?

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?

like image 743
dokaspar Avatar asked Oct 20 '11 16:10

dokaspar


People also ask

What is $data in Ko?

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.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

What is the abbreviation used for KnockoutJS?

KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).

How do you activate a KnockoutJS model?

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.


1 Answers

$data is part of Knockout's Binding Contexts.

Here are all the built-in variables:

  • $parent
  • $parents
  • $root
  • $component
  • $data
  • $index (only available within foreach bindings)
  • $parentContext
  • $rawData
  • $componentTemplateNodes
like image 90
Derek Smith Avatar answered Sep 21 '22 06:09

Derek Smith