How to sort interconnected events with Jquery?

Asked

Viewed 81 times

0

I am developing a Web System that has a page that can contain 4 Script blocks. I wrote a Script that can be found in one of these blocks, but I don’t know which one, it is manipulated by the Controller.

I entered some events Onclick on a button, but sometimes they perform on a order that I didn’t expect.

Is there a way to ensure order execution?

1 answer

0

Follow a jQuery plugin that connects an event listener that is triggered always before others:

(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);

Notes:

1 - This has not been fully tested.

2 - Relies on the internal jQuery structure not changing (tested only with 1.5.2).

3 - It will not necessarily be triggered before the listeners of events that are bound in any way beyond an attribute of the source element or using jQuery bind() and other associated functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.