An alternative to traditional class inheritance, a mixin is a class whose methods are added to, or mixed in, with another class.
Instead of inheriting, the base class includes the methods from a mixin and thus allows to add to or augment the behavior of the base class by adding various mixins to it.
To use Javascript mixins in Magento 2 means to use it to overwrite component methods in Magento 2! I’ll show the use of Javascript mixins in Magento 2 with the example of the change in payment method selection among multiple options in the frontend.
Method to use Javascript Mixins in Magento 2:
- Create file requirejs-config.js at Vendor/Extension/view/frontend
Vendor/Extension/view/frontend var config = { config: { mixins: { 'Magento_Checkout/js/action/select-payment-method': { 'Vendor_Extension/js/action/select-payment-method': true } } // this is how js mixin is defined } };
- Create file select-payment-method.js at Vendor/Extension/view/frontend/web/js/action
define( [ 'ko', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/full-screen-loader', 'jquery', 'mage/storage', 'mage/url', 'Magento_Checkout/js/action/get-totals', ], function (ko, quote, fullScreenLoader, jQuery, storage, urlBuilder, getTotalsAction) { 'use strict'; return function (paymentMethod) { quote.paymentMethod(paymentMethod); //you can write your code according to your need } } );
The above method is helpful when you have to do some task before a JS script’s function run or to extend a function or to modify some data without overwriting JS.
Hope it helps!
Thank you.