Question

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:

$.when(ajaxCall(productUrl)).done(function(response){
        //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

Was it helpful?

Solution

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]:

$.when(ajaxCall(productUrl)).done(function(response){
        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
})
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top