Overriding function from the modal.js file
-
01-03-2021 - |
Вопрос
How can I override a function from the modal.js file in the path vendor/magento/module-ui/view/base/web/js/modal/modal.js
?
In this file, line 307, is a function with name closeModal() that I want to overwrite in my module app/code/VendorName/ModuleName/view/frontend/web/js/model/modal.js
This is the original function:
closeModal: function () {
var that = this;
this._removeKeyListener();
this.options.isOpen = false;
this.modal.one(this.options.transitionEvent, function () {
that._close();
});
this.modal.removeClass(this.options.modalVisibleClass);
if (!this.options.transitionEvent) {
that._close();
}
return this.element;
},
In my modal.js
file I tried to write the following code so that the function is overwritten but unfortunately does not work.
define([
'jquery',
'Magento_Ui/js/modal/modal',
'mage/translate'
], function ($, modal, $t) {
'use strict';
return {
closeModal: function (element) {
console.log("override works");
}
};
});
Can you tell me please where is wrong and how can I override this function?
Thank you!
UPDATE:
My requirejs-config.js
has the following code:
var config = {
map: {
'*': {
'Magento_Ui/web/js/modal/modal':'Bhavin_GDPR/js/view/modal/modal'
}
}
};
I create a file with name modal.js
in the following path app/code/Bhavin/GDPR/view/frontend/web/js/view/modal/modal.js
Content modal.js
define([
'jquery',
'Magento_Ui/js/modal/modal',
'mage/translate'
], function ($, modal, $t) {
'use strict';
return {
closeModal: function (element) {
console.log("override works");
}
};
});
Решение
The best practice is to use mixins.
I also note that requirejs-config.js
is wrong. We don't need web
folder in the path.
Magento_Ui/web/js/modal/modal => Magento_Ui/js/modal/modal
Using mixins:
app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Ui/js/modal/modal': {
'Vendor_Module/js/mixins/modal/modal': true
}
}
}
};
app/code/Vendor/Module/view/frontend/web/js/mixins/modal/modal.js
define([
'jquery',
'underscore',
'mage/template',
'text!ui/template/modal/modal-popup.html',
'text!ui/template/modal/modal-slide.html',
'text!ui/template/modal/modal-custom.html',
'Magento_Ui/js/lib/key-codes',
'jquery/ui',
'mage/translate'
], function ($, _, template, popupTpl, slideTpl, customTpl, keyCodes) {
return function (widget) {
$.widget('mage.modal', widget, {
/**
* Close modal.
* * @return {Element} - current element.
*/
closeModal: function () {
console.log('Alert Here');
var that = this;
this._removeKeyListener();
this.options.isOpen = false;
this.modal.one(this.options.transitionEvent, function () {
that._close();
});
this.modal.removeClass(this.options.modalVisibleClass);
if (!this.options.transitionEvent) {
that._close();
}
return this.element;
}
});
return $.mage.modal;
};
});
Testing: