What is the difference between $root and $parent?

前端 未结 1 530
醉梦人生
醉梦人生 2021-01-30 18:24

I am learning KnockoutJS, but I do not understand the difference between $root and $parent usage. Please see this jsfiddle, or the below code:

相关标签:
1条回答
  • 2021-01-30 18:36

    They are similar but different:

    • $root refers to the view model applied to the DOM with ko.applyBindings;
    • $parent refers to the immediate outer scope;

    Or, visually, from $data's perspective:

    Or, in words of the relevant documentation:

    • $parent: This is the view model object in the parent context, the one immeditely outside the current context.

    • $root: This is the main view model object in the root context, i.e., the topmost parent context. It’s usually the object that was passed to ko.applyBindings. It is equivalent to $parents[$parents.length - 1].

    • $data: This is the view model object in the current context. In the root context, $data and $root are equivalent.

    You'll only see a practical difference if you have view models nested more than one level, otherwise they will amount to the same thing.

    It benefit is rather simple to demonstrate:

    var Person = function(name) {
      var self = this;
      self.name = ko.observable(name);
      self.children = ko.observableArray([]);
    }
      
    var ViewModel = function() {
      var self = this;
      self.name = 'root view model';
      self.mainPerson = ko.observable();
    }
    
    var vm = new ViewModel(),
        grandpa = new Person('grandpa'),
        daddy = new Person('daddy'),
        son1 = new Person('marc'),
        son2 = new Person('john');
    
    vm.mainPerson(grandpa);
    grandpa.children.push(daddy);
    daddy.children.push(son1);
    daddy.children.push(son2);
    
    ko.applyBindings(vm);
    th, td { padding: 10px; border: 1px solid gray; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <script type="text/html" id="person">
      <tr>
        <td data-bind="text: $root.name"></td>
        <td data-bind="text: $parent.name"></td>
        <td data-bind="text: $data.name"></td>
      </tr>
      <!-- ko template: { name: 'person', foreach: children } --><!-- /ko -->
    </script>
    
    <table>
      <tr>
        <th>$root</th>
        <th>$parent</th>
        <th>$data</th>
      </tr>
      <!-- ko template: { name: 'person', data: mainPerson } --><!-- /ko -->
    </table>

    The $root is always the same. The $parent is different, depending on how deeply nested you are.

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