knockout JS $parent object change its information inside for-each loop

Viewed 398

I have a knockout js code in magento2 order summery detail page.

here is the code

<p data-bind="text:console.log('parent befor', $parent)"></p> 
    <!--ko foreach: { data: JSON.parse($parent.options), as: 'option' } -->
        <p data-bind="text:console.log('parent after', $parent)"></p> 

The $parent variable changes its content once we go inside foreach loop. I need some other information of this $parent variable once inside loop but it all get replaced by some unknown information. Here is my console.log. How i can use the original $parent information inside foreach loop.

parent befor {item_id: "300", name: "Vertual Product", qty: 1, price: "3.0000", base_price: "3.0000"}

parent after UiClass {_super: undefined, ignoreTmpls: {…}, _requested: {…}, containers: Array(1), exports: {…}, …}
2 Answers

The reason for the behaviour that you are seeing is that the context has changed, therefore, what is considered the parent has changed. You have gone from being outside a loop to being inside a loop.

Have a look at the $parents array property. You should find what you are looking for there. Based on the description above, what you are looking for should be found in $parents[1] https://knockoutjs.com/documentation/binding-context.html

$parent inside foreach binding refers context of foreach loop and not the parent context.

Use $parents[1]

It will refer to the parent context.

Related