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.
You should be able to nest multiple
foreachloops, even if they get their data from a parent layer. You have to realize that each of those loops creates a new layer in the binding context. Getting the right$parentcan become a tricky exercise...My advice is to move some of the looping logic to your viewmodel.
Here's an example that does a nested loop:
Here's an example that moves some logic to JS: