Attaching jQuery event handlers so that they are triggered first

前端 未结 9 1843
太阳男子
太阳男子 2020-12-05 09:36

Is there a way to attach a jQuery event handler such that the handler is triggered before any previously-attached event handlers? I came across this article, but the code d

9条回答
  •  猫巷女王i
    2020-12-05 10:16

    My best attempt.
    I had code that was structured as follows:

    var $body = jQuery('body');
    $body.on({
        'click': function(event){
        }
    });
    

    To then ensure that the callback was the first one called, I used this function:

    /**
     * promoteLastEvent
     * 
     * @access  public
     * @param   jQuery $element
     * @param   String eventName
     * @return  void
     */
    function promoteLastEvent($element, eventName) {
        var events = jQuery._data($element.get(0), 'events'),
            eventNameEvents = events[eventName],
            lastEvent = eventNameEvents.pop();
        eventNameEvents.splice(1, 0, lastEvent);
    };
    

    This is called as follows:

    promoteLastEvent($body, 'click');
    

    It works quite well for me, given my limited use of $.fn.on.

提交回复
热议问题