Reverse event bubbling in javascript

后端 未结 3 1025
时光说笑
时光说笑 2021-02-08 00:45

As you know, events usually bubble up in javascript, so the event handler of the element that fires the event is executed first, then the event handler of the parent element is

相关标签:
3条回答
  • 2021-02-08 01:33

    I can see one huge drawback of your solution is fact, that for every handled event you have to traverse DOM upwards starting with this to establish number of parents.

    Traversing in such manner in every event handler = low performance.

    0 讨论(0)
  • 2021-02-08 01:37

    Reverse event bubbling is called capture phase.

    See the DOM event architecture

    Pass true as the 3rd argument to Event.addEventListener to have it trigger on capture phase

    el.addEventListener("click", function () {
      console.log("i run in capture");
    }, true);
    

    Of course it won't work in legacy platforms. You'll need a DOM3 events shim to emulate the event system. Feel free to contribute to the DOM-shim

    0 讨论(0)
  • 2021-02-08 01:37

    You could try to emulate it, but probably it could make lots of troubles.

    Here is very very simple example (and on jsfiddle). The idea is to aggregate callbacks from each event, and calling them in reverse order in document event handler (we also clear our list, to ensure new queue on next click).

    <div id="a">
        <div id="b">
            <a href="/test">Click Me!</a>
        </div>
    </div>
    
    var cb = [];
    
    $(document).click(function(evt){
    
        cb.unshift(function(){
            console.log('document');
        });
        var i;
        for(i=0; i<cb.length; ++i){
            cb[i].call(null, evt);
        }
        cb = [];
    });
    
    $("#a").click(function(){
        cb.unshift(function(){
            console.log('div#a');
        });
    });
    
    $("#b").click(function(){
        cb.unshift(function(){
            console.log('div#b');
        });
    });
    
    $('a').click(function(evt){
        cb.unshift(function(evt){
            evt.preventDefault();
            console.log('a');
        });
    });
    

    Maybe you need to change your design? Could you post more information, why you need event capturing?

    0 讨论(0)
提交回复
热议问题