user2243747
user2243747

Reputation: 2967

knockoutjs - accessing $parent/$root inside foreach binding

Here is a plunker code that I am working on. I have defined a VM which looks like this.

    var employee = function(fname,lname){
    var self= this;
    self.fname = ko.observable(fname);
    self.lname = ko.observable(lname);
    self.selectedElement = ko.observable('Default Value');
  }

  var vm = function(){
      var self = this;
      self.employees = new ko.observableArray([]);
      self.selectedElement = ko.observable(-1);

      var e1 = new employee('f1','l1');
      var e2 = new employee('f2','l2');
      self.employees.push(e1);
      self.employees.push(e2);
  };

  ko.applyBindings(vm,container);

And my code to display list of employees is

<body id="container">
<h1>Empoyees</h1>
<div>
  <div data-bind="foreach: employees">
    <h4 data-bind="text: 'Employee' + $index()"></h4>
    <span>First Name :</span>
    <span data-bind="text: fname"></span>
    <br/>

    <span>Last Name :</span>
    <span data-bind="text: fname"></span>
    <br/>

    <span data-bind="text: selectedElement()"></span>
    <!-- I want to access parents 'selectedElement' i.e. vm.slectedElement() -->
    <!--I tried below code but its causing binding error.-->
    <!-- <span data-bind="text: $parent.selectedElement()"></span> -->
    <br/>
  </div>
</div>

Note that lass 'employee' and main view model 'vm' both has identical property named ( selectedElement )

Now inside foreach binding I am trying to access 'selectedElement' property of root/parent context but because I am inside foreach ko is accessing 'selectedElement' property of 'employee' class.

I tried using $root and $parent keywords to reach parent element property but its causing binding error.

Am I missing anything? Here is the plunker link again.

Upvotes: 0

Views: 1366

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You were never creating an instance of your root view model. Change the initial call to

ko.applyBindings(new vm(),container);

https://plnkr.co/edit/wRKfnJi9Jl9Rj2unbgQp?p=preview

When you do that, either $root or $parent will work as expected.

Upvotes: 3

Related Questions