Question

In the Magento 2 documentation, they state

In Magento 2, there are two ways to initialize a JS component

However, they never really explain what a JS component is, and it's not clear from the documentation if "components" are a custom system in Magento 2, a RequireJS module, or something else.

What are the "JS Components" that programmers can initialize with the data-mage-init attribute or the text/x-magento-init script tags.

Was it helpful?

Solution

A JS component is a RequireJS module.

Magento will load these based on JSON given in custom script tags or data-* attributes. The crucial difference is that this module has to return a function. This function will be called with two arguments: the configuration object passed via the JSON, and the element (singular, non-jQuery object) that the component is called on. It is called once per matched element.

Edit: Is this a Magento thing?

This pattern is not specific to Magento. Instead, it comes from jQuery UI widgets. At their core, after all the configuration, they essentially boil down to a function that takes configuration as its first argument, and an element as its second. To see an example of this, look at the collapsible widget. It builds itself as a jQuery plugin, then returns the constructor at the end. If you inspect this function, you'll see the same argument order. Magento hijacked this pattern so that it can use jQuery UI.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top