Ability to add listeners directly to objects like Modals/Collapse/etc
How about a public method to add listener(s) to an object, something like:
class Modal {
//...
on(event, callback) {
this._element.addEventListener(`${event}${EVENT_KEY}`, callback);
return this;
}
//...
}
This will allows us to do something like:
var myModal = new bootstrap.Modal(document.getElementById('myModal'));
myModal
.on('shown', function (e) {
// do something...
})
.on('hidden', function (e) {
// do something...
});
Instead of:
var myModal = new bootstrap.Modal(document.getElementById('myModal'));
myModal._element.addEventListener('shown.bs.modal', function (e) {
// do something...
});
myModal._element.addEventListener('hidden.bs.modal', function (e) {
// do something...
});
Hi @arcanedev-maroc,
Thanks I think it's a good idea, it'll be easier to listen to our events 👍
Any other thoughts @twbs/js-review ?
I think this would make a prudent addition.
PRs welcome, but the sooner the better before v5 hits stable :)
Hi @XhmikosR, i've created a PR: #32184
I would love if that supported chaining. E.g.
let modal = new Modal(element)
.on('shown', e => { })
.show()
how to ensure that bootstrap listen to changes while open?
import SwagCustomizedProductsFormValidator
from '../../../../../../../SwagCustomizedProducts/src/Resources/app/storefront/src/swag-customized-products-form-validator/swag-customized-products-form-validator.plugin'
export default class SynCustomProductsFormValidator extends SwagCustomizedProductsFormValidator {
init() {
super.init();
let modal = document.getElementById('content-modal');
// Create a MutationObserver to observe changes to the modal's inline style
let observer = new MutationObserver((mutationsList, observer) => {
// Iterate over all mutations
for (let mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
// Check if the 'display' style has changed
if (modal.style.display === 'block' || getComputedStyle(modal).display === 'block') {
console.log('modal is open');
let synButton = document.getElementById('syn-add-to-cart-button');
synButton.disabled = this._context.buyButton.disabled;
} else {
console.log('modal is closed');
}
}
}
});
// Configure the observer to watch for changes to the 'style' attribute
let config = {attributes: true, childList: false, subtree: false};
// Start observing the modal
observer.observe(modal, config);
// To stop observing, use:
// observer.disconnect();
}
}
i have the problem that i am detecting a button outside of the modal if it is disabled or enabled to give the same state to my modal button, when the modal is loaded it loads the state correctly from the defult button, but after messing with an input inside the modal, it loses its state, does anyone have any idea ??