In this article, we will create a mixin JS file to override the core or any 3rd party extension’s knockoutJS function. We will need to create 2 files: the requirejs-config.js file and the file in which we will be overriding the core function of any knockoutJS file.
Table of Contents
requirejs-config.js
The purpose of this file is to manage module loading, dependencies and customization for KnockoutJS scripts in Magento 2. The file can be found in frontend, admin, and base, depending on the requirement to override or replace the entire file.
In this article, we will use our custom module name Learningmagento_Jsoverrider
. We will first create the requirejs-config.js file under Learningmagento/Jsoverrider/view/frontend. We will be modifying one of the core Magento knockoutjs files, which will be on the frontend. We are not adding other module files which are need. You can check it in this article Create Magento 2 Custom Module Development.
var config = {
config: {
mixins: {
'Magento_Swatches/js/swatch-renderer': {
'Learningmagento_Jsoverrider/js/swatch-filter-mixin': true
}
}
}
};
We are overriding one of the function inside swatch-render.
mixin file
Here, we will create the mixin file to override the swatch-render.js file. We are creating a swatch-filter-mixin.js file, which we can put under Learningmagento/Jsoverrider/view/frontend/web/js. We will override one of the methods _RenderControls
. This method is triggered when the swatches are rendered.
define(['jquery'], function ($) {
'use strict';
return function (SwatchRenderer) {
$.widget('mage.SwatchRenderer', SwatchRenderer, {
_RenderControls: function () {
this._super();
$('.swatch-attribute-options').each(function() {
$(this).find('.swatch-option').first().click();
});
}
});
return $.mage.SwatchRenderer;
};
});
Our code will click the first swatch on every product in the list. We have overridden _RenderControls
function, in which we have written this.super()
, which means we are first running the code of the parent file, then we are clicking the first swatch.
Summery
It is very simple to override a function of any JS file. However, if you want to override the complete JS file, then there is a different approach using map. Sometimes the override doesn’t work. This is usually the case when there is already an overriding file present in some 3rd party extension. In such a case, you need to override the overriding file by passing false.
One comment
Comments are closed.