How to Use Javascript Mixins in Magento 2
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
12345678910Vendor/Extension/view/frontendvar 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
123456789101112131415161718define(['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!
I would appreciate your opinions about the post in the Comments section below. Also, you can post your doubts regarding Javascript mixins in Magento 2 and I’d be happy to help 🙂
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
Magento Imagine 2019 – Recap & Insights
Solution: Discount Based on Payment Method Not Showing in Magento 2 Cart Total
Next