In this short tutorial we will learn how to extend Magento 2 jQuery widget with our custom logic.
To extend a default Magento jQuery widget, create <your_widget_name>.js
with the following contents:
define([ 'jquery', 'jquery/ui', 'mage/<widget.name>' // usually widget can be found in /lib/web/mage dir ], function($){ $.widget('<your_namespace>.<your_widget_name>', $.mage.<widget.name>, { ... }); return $.<your_namespace>.<your_widget_name>; });
Where the following notation is used:
<your_namespace>.<your_widget_name>
the name of your custom widget. According to the jQuery widgets naming convention, must contain a namespace and name.mage.<widget.name>
the name of the Magento widget that you extend.
For information about how to initialize your custom widget in a .phtml
template, see the JavaScript initialization topic.
Practical Example of extending Magento 2 jQuery Widget
Let’s see what we need to do to extend $.mage.configurable
First, we need to make our module has Magento_ConfigurableProduct
defined as sequence in module.xml
:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Vendor_ModuleName" setup_version="1.0.0"> <sequence> <module name="Magento_ConfigurableProduct"/> </sequence> </module> </config>
Secondly add requirejs-config.js
file in view/frontend
directory with code:
var config = { map: { '*': { configurable: 'Vendor_ModuleName/js/configurable' } } };
Finally add configurable.js
file in view/frontend/web/js
directory with:
define([ 'jquery', 'jquery/ui', 'Magento_ConfigurableProduct/js/configurable' ], function($){ $.widget('custom.configurable', $.mage.configurable, { // the code you want to override }); return $.custom.configurable; });
Make sure to regenerate the component list in config.php
and this is how you extend Magento 2 jQuery Widget.
You can check my previous posts about Magento 2.