Magento 2 Knockoutjs Data-Bind Not Working in Inner Loop

knockoutknockoutjs

Case 1:Working

HTML

Test::<span data-bind="text: $parent.testText"></span>
<button  data-bind="click: $parent.testbtn"></button>

JS

numberOfClicks : ko.observable(0),
incrementClickCounter : function() {
 alert('click called..');
 var previousCount = this.numberOfClicks();
 this.numberOfClicks("Testtttt....");
}

Case 2:Working

HTML

<!-- ko foreach: { data: loop1(), as: 'styleColor'} -->
 Test::<span data-bind="text: $parent.testText"></span>
 <button  data-bind="click: $parent.testbtn"></button>
<!-- /ko -->

Case 3:Not working

HTML

<!-- ko foreach: { data: loop1(), as: 'styleColor'} -->
 <div class="standard-color" data-bind="foreach: $parent.loop2()">                    
     Test::<span data-bind="text: $parent.testText"></span>
     <button  data-bind="click: $parent.testbtn"></button>
 </div>
<!-- /ko -->

When i click on button, js function not calling.
Thanks in advanced.

Best Answer

That's because you have added an additional layer, so $parent is now referencing the inner loop not the outer loop. To access the outer loop again try $parents[1].

See https://stackoverflow.com/questions/17069381/access-parents-parent-in-knockout-view-nesting-context for more info.

Related Topic