In this article, I will let you know how to use Mixins in Magento 2.
What is a Mixin?
“A Mixin is a language concept that allows a programmer to inject some coding into a class. Mixin programming is a style of software development in which units of functionality are created in a class, and then mixed in with other classes”. Extracted from Wikipedia
Let’s get started
Let’s imagine the following scenario; you want to perform an extra action or extend a Javascript functionality without completely overwriting it. First of all, You need to place the file require-config.js
in the module where you want to extend that JS functionality as is shown in the following path app/code/Vendor/Module/view/frontend/
If it does not exist, You need to create it into the previously mentioned directory above.
To show in-depth the creation of a mixin, I will exemplify how to add a new action when adding a product to the cart in Magento 2 product view
Our file require-config.js
should have the following content
var config = {
config: {
mixins: {
'Magento_Catalog/js/catalog-add-to-cart': {
'Vendor_Module/js/catalog-add-to-cart-mixin': true
}
}
}
};
Now let’s create the file catalog-add-to-cart-mixin.js
. That will extend the JS functionality in the following directory Vendor/Module/view/frontend/web/js/catalog-add-to-cart-mixin.js
. Use the following content
define([
], function () {
'use strict';
return function (widget) {
$.widget('mage.catalogAddToCart', widget, {
/**
* Handler for the form 'submit' event
*
* @param {jQuery} form
*/
submitForm: function (form) {
this.ajaxSubmit(form); // original code
this.doSomething(); // add every thing you want
},
/**
* Do something
*/
doSomething: function () {
// Do stuff
},
});
return $.mage.catalogAddToCart;
}
});
Wrapping up
Mixins help you to modify features for special and more specific uses of your e-commerce. Remember that you have them as part of your ‘Swiss army knife’!
Keep reading and Happy coding!