In this post, we will understand how to use Mixins in Magento 2.
What is Mixin?
Mixins are a language concept that allows a programmer to inject some code into a class
A mixin is a class containing methods that can be used by other classes without a need to inherit from it.
Wikipedia
If we want to perform an extra action or extend a Javascript functionality without completely overwriting it, in this case mixin comes in picture. Let’s start with an example
var config = {
config: {
mixins: {
'Magento_Catalog/js/catalog-add-to-cart': {
'Codedecorator_Learn/js/cd-catalog-add-to-cart-mixin': true
}
}
}
};
After creating above file, we need to create cd-catalog-add-to-cart-mixin.js file where we will extend the functionality of the submitForm function.
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.doSomethingAfterSubmit(); // add every thing you want
},
/**
* Do something
*/
doSomethingAfterSubmit: function () {
// Do stuff
},
});
return $.mage.catalogAddToCart;
}
});
Try to add product into cart and see your change is coming in or not. If not then try to flush cache or deploy the content.
Happy coding guys 😀