How to override Magento 2 js using Mixins?
How to override Magento 2 js using Mixins?
A Magento 2 RequireJS “mixins” allows you to programmatically listen for the initial instantiation of any RequireJS, How do mixins in Magento 2 work?
First, create requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Checkout/js/model/quote': {
'PackageName_ModuleName/js/plugin-quote': true
}
}
}
};
Code language: JavaScript (javascript)
Magento_Checkout/js/model/quote js file you want to rewrite.
PackageName_ModuleName/js/plugin-quote target file.
plugin-quote.js
/*global define*/
define(["jquery"], //defile more js here
function ($) {
'use strict';
var mixins = {
getTotals: function () { //Define new content for getTotal() function
//Before get total code here
var _return = this._super(arguments); //Call default quote get Totals function.
//After get totals code here
return _return;
};
return function (target) { //target = quote returned by Magento_Checkout/js/model/quote
return target.extend(mixins); //Return quote again, it important if you don't return you can't use Magento_Checkout/js/model/quote by required.
}
}
});
Code language: JavaScript (javascript)
You can’t access the private variable from Magento_Checkout/js/model/quote.
What is a private variable
define(['ko'], function (ko) {
'use strict';
var abc; //private
var def; //private
return {
//Code logic here. you can access any variable/function defined in here
}
});
Code language: JavaScript (javascript)
If your source file is returned $.mage.[widgetName] ex : Magento_Catalog/js/price-box.js
Your destination file must return $.mage.[widgetName]
return function (priceBox) {
$.widget('mage.priceBox', priceBox, {
/**
* Widget creating.
*/
_create: function createPriceBox() {
var box = this.element;
//this._setDefaultsFromPriceConfig();
this._setDefaultsFromDataSet();
box.on('reloadPrice', this.reloadPrice.bind(this));
box.on('updatePrice', this.onUpdatePrice.bind(this));
}
});
return $.mage.priceBox;
};
Code language: JavaScript (javascript)
2 thoughts on “How to override Magento 2 js using Mixins?”
This code not works thanks!
Did you clean the browser cache and making sure the requirejs-config.js uptodate? Do you have any error on console.log?