How to order events bound with jQuery

后端 未结 12 1190
闹比i
闹比i 2020-11-22 13:09

Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is ha

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 13:30

    I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.

    If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:

    ** UPDATED inline with jQuery changes (thanks Toskan) **

    (function($) {
        $.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
            var indexOfDot = eventType.indexOf(".");
            var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";
    
            eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
            handler = handler == undefined ? eventData : handler;
            eventData = typeof eventData == "function" ? {} : eventData;
    
            return this.each(function() {
                var $this = $(this);
                var currentAttrListener = this["on" + eventType];
    
                if (currentAttrListener) {
                    $this.bind(eventType, function(e) {
                        return currentAttrListener(e.originalEvent); 
                    });
    
                    this["on" + eventType] = null;
                }
    
                $this.bind(eventType + eventNameSpace, eventData, handler);
    
                var allEvents = $this.data("events") || $._data($this[0], "events");
                var typeEvents = allEvents[eventType];
                var newEvent = typeEvents.pop();
                typeEvents.unshift(newEvent);
            });
        };
    })(jQuery);
    

    Things to note:

    • This hasn't been fully tested.
    • It relies on the internals of the jQuery framework not changing (only tested with 1.5.2).
    • It will not necessarily get triggered before event listeners that are bound in any way other than as an attribute of the source element or using jQuery bind() and other associated functions.

提交回复
热议问题