MDL-82793 core: Make modal execute JS from template

Co-authored-by: Huong Nguyen <huongnv13@gmail.com>
This commit is contained in:
Philipp Memmel 2024-08-14 12:45:40 +02:00
parent fc29adddf9
commit 43073fcd27
3 changed files with 20 additions and 3 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -131,6 +131,7 @@ export default class Modal {
this.attachmentPoint = document.createElement('div');
document.body.append(this.attachmentPoint);
this.focusOnClose = null;
this.templateJS = null;
if (!this.root.is(SELECTORS.CONTAINER)) {
Notification.exception({message: 'Element is not a modal container'});
@ -194,9 +195,12 @@ export default class Modal {
const templateName = this._getTemplateName(modalConfig);
const templateContext = modalConfig.templateContext || {};
const {html} = await Templates.renderForPromise(templateName, templateContext);
const {html, js} = await Templates.renderForPromise(templateName, templateContext);
const modal = new this(html);
if (js) {
modal.setTemplateJS(js);
}
modal.configure(modalConfig);
pendingModalPromise.resolve();
@ -303,6 +307,11 @@ export default class Modal {
// If we'd cached any JS then we can run it how that the modal is
// attached to the DOM.
if (this.templateJS) {
Templates.runTemplateJS(this.templateJS);
this.templateJS = null;
}
if (this.bodyJS) {
Templates.runTemplateJS(this.bodyJS);
this.bodyJS = null;
@ -1212,4 +1221,12 @@ export default class Modal {
button.removeAttr('disabled');
}
}
/**
* Set the template JS for this modal.
* @param {String} js The JavaScript to run when the modal is attached to the DOM.
*/
setTemplateJS(js) {
this.templateJS = js;
}
}