Last Updated: February 25, 2016
·
212
· linzhp

Handlers Disorder

Ideally, if Event1 is trigger before Event2, all handlers of Event2 should be executed after all handlers of Event1 are done. However, this is not the case in HTML or jQuery. I wrote a failed Jasmine Spec to demonstrate this:

describe('A jquery element', function() {
    it('should invoke handlers in the order of events triggered from it', function() {
        var tokens = [];
        var elem = document.createElement('div');
        function e1Handler1(payload) {
            tokens.push('e1Handler1');
            $(elem).trigger('Event2');
        }
        function e1Handler2(payload) {tokens.push('e1Handler2');}
        function e2Handler1(payload) {tokens.push('e2Handler1');}
        $(elem).bind('Event1', e1Handler1);
        $(elem).bind('Event1', e1Handler2);
        $(elem).bind('Event2', e2Handler1);
        $(elem).trigger('Event1', {});
        expect(tokens).toBe(['e1Handler1', 'e1Handler2', 'e2Handler1']);
    });
});

describe('An HTML element', function() {
    it('should invoke handlers in the order of events triggered from it', function() {
        var tokens = [];
        var elem = document.createElement('div');
        var e1 = new CustomEvent('Event1');     
        var e2 = new CustomEvent('Event2');
        function e1Handler1(payload) {
            tokens.push('e1Handler1');
            elem.dispatchEvent(e2);
        }
        function e1Handler2(payload) {tokens.push('e1Handler2');}
        function e2Handler1(payload) {tokens.push('e2Handler1');}
        elem.addEventListener('Event1', e1Handler1);
        elem.addEventListener('Event1', e1Handler2);
        elem.addEventListener('Event2', e2Handler1);
        elem.dispatchEvent(e1);
        expect(tokens).toBe(['e1Handler1', 'e1Handler2', 'e2Handler1']);        
    });
});