Use of Js Mixins in Magento2
Today I am going to explain that how you can use js mixins in magento 2 in this article. Suppose you have to do some task before any js script’s function run or to extend a function or to modify some data without overwrite of js so this blog will be very helpful for you.
At first you will need to create requirejs-config.js under app/code/Company/Module/view/frontend, like below:
1 2 3 4 5 6 7 8 9 10 |
var config = { config: { mixins: { 'Magento_Checkout/js/action/set-shipping-information': { 'Company_Module/js/action/set-shipping-information-mixin': true } } // this is how js mixin is defined } }; // I am extending "Magento_Checkout/js/action/set-shipping-information" this js with our custom js "Company_Module/js/action/set-shipping-information-mixin". |
Now, create set-shipping-information-mixin.js file under app/code/Company/Module/view/frontend/web/js/action to extend original function. So I am just appending some data to shipping address only for example, here is the code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/*jshint browser:true jquery:true*/ /*global alert*/ define([ 'jquery', 'mage/utils/wrapper', 'Magento_Checkout/js/model/quote' ], function ($, wrapper, quote) { 'use strict'; return function (setShippingInformationAction) { return wrapper.wrap(setShippingInformationAction, function (originalAction) { var shippingAddress = quote.shippingAddress(); if (shippingAddress['extension_attributes'] === undefined) { shippingAddress['extension_attributes'] = {'customvar':"value1"}; } // you can write here your code according to your requirement return originalAction(); // it is returning the flow to original action }); }; }); |
Now if you console quote.shippingAddress() in js then result will be as follows :
Hope this blog will help you to develop custom functionality in your module in a better way. Try this and if you have any query then just comment below 🙂
Be the first to comment.