3

I try to better understand the concept of text/x-magento-init.

I understand that it allows us to define script components that do a certain task, which we then can use as often as we like in any template.

I found this example in vendor\magento\module-theme\view\frontend\templates\js\cookie.phtml

<script type="text/x-magento-init">
    {
        "*": {
            "mage/cookies": {
                "expires": null,
                "path": "<?= $block->escapeJs($block->getPath()) ?>",
                "domain": "<?= $block->escapeJs($block->getDomain()) ?>",
                "secure": false,
                "lifetime": "<?= $block->escapeJs($block->getLifetime()) ?>"
            }
        }
    }
</script>

By reading the documentation, I figured out that this means, a script is getting called once (because of the *). But where do I find the component mage/cookies to understand what it does exactly? And what if I use body instead of *, how does this change the logic?

Bonus Question: How to define our own component?

1 Answer 1

3

mage/cookies is JS component which initialized on the element with the selector specified as element selector.

Syntax :

<script type="text/x-magento-init">
{
    // components initialized on the element defined by selector
    "<element_selector>": {
        "<js_component1>": ...,
        "<js_component2>": ...
    },
    // components initialized without binding to an element
    "*": {
        "<js_component3>": ...
    }
}
</script>

If you'll add body instead of * then, it will consider as element_selector.

If you'll add * then it will provide data without selector.

For more details, You can check here.

7
  • But where is mage/cookies defined, where can I inspect its code?
    – Black
    Commented Feb 18, 2020 at 13:16
  • You can check here : lib/web/mage/cookies.js Commented Feb 18, 2020 at 13:42
  • And if I want to create my own, do I have to put it in my theme or there? And when does it make sense to use an element selector?
    – Black
    Commented Feb 18, 2020 at 13:59
  • You can use in theme as well as in module also. It's depend on your requirement. Commented Feb 19, 2020 at 4:25
  • I guess I have to create the same folder structure in my theme e.g. mytheme/base/lib/mycustom.js ?
    – Black
    Commented Feb 19, 2020 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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