Twitter Bootstrap. Why do modal events work in JQuery but NOT in pure JS?

前端 未结 2 986
庸人自扰
庸人自扰 2020-11-30 06:06

The Twitter Bootstrap modal dialog has a set of events that can be used with callbacks.

Here is an example in jQuery:

    $(modalID).on(\'hidden.bs.m         


        
2条回答
  •  难免孤独
    2020-11-30 06:13

    Native Javascript Solution. Here is my way of doing it without JQuery.

    //my code ----------------------------------------
    export const ModalHiddenEventListener = (el, fn, owner) => {
        const opts = {
            attributeFilter: ['style']
        },
        mo = new MutationObserver(mutations => {
            for (let mutation of mutations) {
                if (mutation.type === 'attributes' 
                && mutation.attributeName ==='style' 
                && mutation.target.getAttribute('style') === 'display: none;') {
                    mo.disconnect();
                    fn({
                        owner: owner,
                        element: mutation.target
                    });
                }
            }
        });
        mo.observe(el, opts);
    };
    //your code with Bootstrap modal id='modal'------- 
    const el = document.getElementById('modal'),
          onHide = e => {
              console.log(`hidden.bs.modal`); 
          };
    ModalHiddenEventListener(el, onHide, this);
    

    Compatibility: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#Browser_compatibility

提交回复
热议问题