0

I am trying to execute some custom code after a knockout template has fully rendered.
The template is Magento_Catalog/list/listing.html

The relevant part of the template for this problem is:

        <div css="'products-' + displayMode">
            <ol class="product-items product-slider recently-viewed" afterRender="function (t) {addSlider(t);}">
                <li class="product-item" repeat="foreach: filteredRows, item: '$row'">
                    <div class="product-item-info">
                        <fastForEach args="data: getRegion('general-area'), as: '$col'" >
                            <render args="$col.getBody()"/>
                        </fastForEach>
                    </div>
                </li>
            </ol>
        </div>

As you can see I added an afterRender function to the ol tag.
The items are added to the list via repeat="foreach:" The problem now is, that whenever there is more than one li in the list the afterRender event fires only once, after the first item is being added.
So my custom code doesn't manipulate the full list like it's supposed to.
How can I execute the code after all items have been added to the list?

0

1 Answer 1

1

According to the docs afterAdd is what you want:

afterAdd — is like afterRender, except it is invoked only when new entries are added to your array (and not when foreach first iterates over your array’s initial contents). A common use for afterAdd is to call a method such as jQuery’s $(domNode).fadeIn() so that you get animated transitions whenever items are added. Knockout will supply the following parameters to your callback:

  • A DOM node being added to the document
  • The index of the added array element
  • The added array element

The relevent section here is "The index of the added array element".

It sounds like you need to use this and check if the index of the current element is the last one in the array - if so then do what you need to do.

1
  • this doesn't work unfortunately. Where the afterRender fires once initially, the afterAdd doesn't fire at all. I guess this is because of the repeat loop not triggering an update on the parent. I tried to change this into a standard foreach loop but failed.
    – Chaz
    Aug 3, 2021 at 7:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.