twbs / bootstrap

The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
https://getbootstrap.com
MIT License
170.88k stars 78.88k forks source link

Ability to add listeners directly to objects like Modals/Collapse/etc #31266

Open arcanedev-maroc opened 4 years ago

arcanedev-maroc commented 4 years ago

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...
});
Johann-S commented 4 years ago

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 ?

bardiharborow commented 4 years ago

I think this would make a prudent addition.

XhmikosR commented 3 years ago

PRs welcome, but the sooner the better before v5 hits stable :)

arcanedev-maroc commented 3 years ago

Hi @XhmikosR, i've created a PR: #32184

alecpl commented 3 years ago

I would love if that supported chaining. E.g.

let modal = new Modal(element)
    .on('shown', e => {  })
    .show()