The Setup:
handlerA & handlerB listen for event1, while handlerC listens for event2
The execution:
1. event1 is sent (handlers A & B are listening)
2. handlerA receives it, and along it's codepath sends event2
3. handlerC receives event2
4. handlerB receives event1
Question: If the 'on' event is supposed to be asynchronous, shouldn't handlerB receive event1 before handlerC receives event2? Can someone explain this to me?
console.clear();
window.EventDispatcher = {
send: function(type, payload) {
$(EventDispatcher).trigger({
type: type,
payload: payload
});
}
};
//---- SEND EVENT ----
$(function() {
$('#sendEventBtn').on('click', function() {
console.log('sending event1 to A and B...')
EventDispatcher.send('event1')
})
})
$(EventDispatcher).on('event1', handlerA);
$(EventDispatcher).on('event1', handlerB);
$(EventDispatcher).on('event2', handlerC);
function handlerA() {
console.log('handlerA received event1');
console.log('handlerA sending event2');
EventDispatcher.send('event2')
}
function handlerB() {
console.log('handlerB received event1');
}
function handlerC() {
console.log('handlerC received event2');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='sendEventBtn'>Send Event</button>
Here's a plunker: http://plnkr.co/edit/Ux0kL3d5Hul8IopUXeRW?p=preview