Say you load via ajax another product on the product page.

There are some mage scripts that do not run and you need to run elem.trigger('contentUpdated') to make magento evaluate the <script type=“text/x-magento-init”> code.

But the issue is that magento will evaluate the entire page again. So doing it like this:

        //parse response

        container.append(parsedResponse); //append in container
        container.trigger('contentUpdated'); //trigger update

Magento will change the product image for current product too, loading the image from the product just loaded.

I want the current product to stay as it is obviously, and just insert the newly loaded product somewhere else (with its image and other data i.e buy, description).

The only issue that I see is with the images that gets regenerated for the current product too if I run .trigger('contentUpdated').

Being more specific with the element on which I trigger does not help, as on whatever element I trigger the update magento will reinterpret the body: https://github.com/magento/magento2/blob/develop/lib/web/mage/mage.js#L93

  • You could try using triggerHandler since it does not bubble, unlike trigger which bubbles up the DOM. – Aaron Allen Jul 27 '16 at 20:12
  • @AaronAllen thanks. triggerHandler doesn't do anything on any elements except if I attach it to $('body'). But if I do this obviously everything runs. I guess contentUpdated event is attached only to body? – Claudiu Creanga Jul 28 '16 at 10:19

The issue arises because <script type="text/x-magento-init"> [data-gallery-role=gallery-placeholder] is too broad and $("#gallery).trigger('contentUpdated') bubbles up to the only element where contentUpdated is attached too, which is body and then mage.apply() runs document.querySelectorAll("[data-gallery-role=gallery-placeholder]") which of course will evaluate every element.

I didn't find a better solution than to use a more specific selector on [data-gallery-role=gallery-placeholder]:

        var script = parsedResponse.find('.product.media script[type="text/x-magento-init"]').html()
        var updatedScript = script.replace("[data-gallery-role=gallery-placeholder]","div.unique-identifier > .gallery-placeholder[data-gallery-role=gallery-placeholder]");
        parsedResponse.find('.product.media script[type="text/x-magento-init"]').replaceWith('<script type="text/x-magento-init">'+updatedScript+'</script>');

        container.append(parsedResponse); //append in container
        container.trigger('contentUpdated'); //trigger update

Your Answer

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

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