jquery“on”事件

时间:2016-07-14 18:24:55

标签: javascript jquery events

设置:

handlerA & handlerB listen for event1, while handlerC listens for event2

执行:

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

问题:如果'on'事件应该是异步的,那么在handlerC收到event2之前,handlerB不应该接收event1吗?有人可以向我解释一下吗?

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>

这是一个掠夺者:http://plnkr.co/edit/Ux0kL3d5Hul8IopUXeRW?p=preview

1 个答案:

答案 0 :(得分:0)

您正在寻找的词是“非阻塞”&amp;这不是“意外”的行为,如果来自handlerA的event2首先被触发,那么显然handlerC会首先得到它,它的全部都是关于时间的。简而言之,如果到达第4行,如果handlerA已经完成,那么handlerC将接收该事件。

function handlerA() {
    console.log('handlerA received event1');
    console.log('handlerA sending event2');
    EventDispatcher.send('event2')
}
  

将event1发送到A和B ......

     

handlerA收到了event1

     

handlerA发送event2

     

handlerC收到了event2

     

handlerB收到了event1

现在有一些延迟(了解更多关于setTimeout with 0)事件2&amp;你会看到。

function handlerA() {
    console.log('handlerA received event1');
    setTimeout(function(){
       console.log('handlerA sending event2');
       EventDispatcher.send('event2');           
    }, 0);
}
  

将event1发送到A和B ......

     

handlerA收到了event1

     

handlerB收到了event1

     

handlerA发送event2

     

handlerC收到了event2