Use js mixins magento 2
In this tutorial we will discuss Use js mixins magento 2 .i.e how to use js mixins in magento 2.And in this tutorial i will try to explain it briefly and also make it convenient.
Suppose your code does some task before any js script’s function run or you want to extend a function or to modify some data without overwriting js. And you want to know how to do it.Then this tutorial will help you learn and overcome all these problems easily.
First of all you will need to create requirejs-config.js under app/code/QaisarSatti/HelloWorld/view/frontend, like below:
config: {
mixins: {
'Magento_Checkout/js/action/set-shipping-information': {
'QaisarSatti_HelloWorld/js/action/set-shipping-information-mixin': true
}
} // this is how js mixin is defined
}
};
// Here i am extending "Magento_Checkout/js/action/set-shipping-information" this js with our custom js "QaisarSatti_HelloWorld/js/action/set-shipping-information-mixin".
Furthermore create set-shipping-information-mixin.js file under app/code/QaisarSatti/HelloWorld/view/frontend/web/js/action to extend original function. So here i am just using dummy data to shipping address only , Below is the code:
/*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 console thequote.shippingAddress() in js to you should see the result:
That’s it from this tutorial. I hope it serves the purpose.Furthermore please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.