There is a knockout js component on category page, that is initialized like this (for every product in a list):

<div id="some-block-<?= $product->getId() ?>" class="some-block-container" data-bind="scope:'some-block-<?= $product->getId() ?>'">
    <!-- ko template: {name: getTemplate()} --><!-- /ko -->

<script type="text/x-magento-init">
   "#some-block-<?= $product->getId() ?>": {
       "Magento_Ui/js/core/app": <?= $viewModel->getJsLayout($product); ?>

It works fine. But category page can load more products that are appended. And obviously component is not initialized for the newly added products.

How can I initialize component for the new dynamically added elements?

I am trying to run

$('.products-grid .some-block-container').each(function() {
    if (!!ko.dataFor(this)) {
        ko.applyBindings(viewModel, this);

But it does not apply anything as ko.dataFor(this) returns undefined. But if I remove it, I receive an error:

You cannot apply bindings multiple times to the same element

Which is quite correct for existing elements.

I know that it would be correct to create parent component in a way, that it handles all the list, but this is 3-d party module that adds functionality and can be disabled in admin. And refactoring of the whole category page is out of scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.