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

前端 未结 3 789
一向
一向 2020-12-24 04:31

In the KnockoutJS tutorials I stumbled upon the following code example that contains an unexplainable variable $data.

The View (html):



        
相关标签:
3条回答
  • 2020-12-24 05:12

    i made it work

    .selected {
        color:red;
    }
    
    <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() },text:$data,
                       click: function() { mailViewModel.selectFolder($data) }">
        </li>    
    </script>
    
    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);
    

    please take a look at http://jsfiddle.net/bowen31337/48RDd/

    0 讨论(0)
  • 2020-12-24 05:15

    $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
    0 讨论(0)
  • 2020-12-24 05:19

    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.folders array.

    0 讨论(0)
提交回复
热议问题