How to order events bound with jQuery

2018-12-31 15:51发布

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 handled by the controller.

I bind some onclick events to a button, but I find that they sometimes execute in an order I did not expect.

Is there a way to ensure order, or how have you handled this problem in the past?

12条回答
闭嘴吧你
2楼-- · 2018-12-31 16:16

In some special cases, when you cannot change how the click events are bound (event bindings are made from others' codes), and you can change the HTML element, here is a possible solution (warning: this is not the recommended way to bind events, other developers may murder you for this):

<span onclick="yourEventHandler(event)">Button</span>

With this way of binding, your event hander will be added first, so it will be executed first.

查看更多
孤独寂梦人
3楼-- · 2018-12-31 16:18

Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.

If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.

$( '#mybutton' ).click( function(e) { 
    // Do stuff first
} );

$( '#mybutton' ).click( function(e) { 
    // Do other stuff first
} );

$( document ).delegate( '#mybutton', 'click', function(e) {
    // Do stuff last
} );

Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last: https://github.com/nickyleach/jQuery.bindLast.

Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.

查看更多
君临天下
4楼-- · 2018-12-31 16:19

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.
查看更多
墨雨无痕
5楼-- · 2018-12-31 16:20

Please note that in the jQuery universe this must be implemented differently as of version 1.8. The following release note is from the jQuery blog:

.data(“events”): jQuery stores its event-related data in a data object named (wait for it) events on each element. This is an internal data structure so in 1.8 this will be removed from the user data name space so it won’t conflict with items of the same name. jQuery’s event data can still be accessed via jQuery._data(element, "events")

We do have complete control of the order in which the handlers will execute in the jQuery universe. Ricoo points this out above. Doesn't look like his answer earned him a lot of love, but this technique is very handy. Consider, for example, any time you need to execute your own handler prior to some handler in a library widget, or you need to have the power to cancel the call to the widget's handler conditionally:

$("button").click(function(e){
    if(bSomeConditional)
       e.stopImmediatePropagation();//Don't execute the widget's handler
}).each(function () {
    var aClickListeners = $._data(this, "events").click;
    aClickListeners.reverse();
});
查看更多
梦醉为红颜
6楼-- · 2018-12-31 16:23

just bind handler normally and then run:

element.data('events').action.reverse();

so for example:

$('#mydiv').data('events').click.reverse();
查看更多
孤独总比滥情好
7楼-- · 2018-12-31 16:23

Here's my shot at this, covering different versions of jQuery:

// Binds a jQuery event to elements at the start of the event chain for that type.
jQuery.extend({
    _bindEventHandlerAtStart: function ($elements, eventType, handler) {
        var _data;

        $elements.bind(eventType, handler);
        // This bound the event, naturally, at the end of the event chain. We
        // need it at the start.

        if (typeof jQuery._data === 'function') {
            // Since jQuery 1.8.1, it seems, that the events object isn't
            // available through the public API `.data` method.
            // Using `$._data, where it exists, seems to work.
            _data = true;
        }

        $elements.each(function (index, element) {
            var events;

            if (_data) {
                events = jQuery._data(element, 'events')[eventType];
            } else {
                events = jQuery(element).data('events')[eventType];
            }

            events.unshift(events.pop());

            if (_data) {
                jQuery._data(element, 'events')[eventType] = events;
            } else {
                jQuery(element).data('events')[eventType] = events;
            }
        });
    }
});
查看更多
登录 后发表回答