Vanilla JS中的WP Heartbeat API(用于自定义事件的addEventListener)

时间:2019-01-02 14:37:45

标签: javascript jquery wordpress wordpress-rest-api

为什么下面用jquery编写的代码可以很好地工作,但是当我尝试将其与vanilla js一起使用时,它将无法正常工作。

这是WP Heartbeat API代码-https://github.com/WordPress/WordPress/blob/master/wp-includes/js/heartbeat.js

jQuery(document).ready( function($) {
  $(document).on('heartbeat-tick', function() {
    console.log('jquery');
  });
});




jQuery(document).ready( function($) {
  document.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS');
  });
});


jQuery(document).ready( function($) {
var event = new Event('heartbeat-tick');
window.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS');
});
window.dispatchEvent(event);
});

1 个答案:

答案 0 :(得分:0)

您的document事件未触发,因为您是在window上调度事件。调用document.dispatchEvent将其分派到document

jQuery(document).ready(function($) {
  var event = new Event('heartbeat-tick');

  $(document).on('heartbeat-tick', function() {
    console.log('jquery');
  });
  
  document.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS from document');
  });

  window.addEventListener('heartbeat-tick', function() {
    console.log('Heartbeat tick JS from window');
  });
  
  console.log('window');
  window.dispatchEvent(event);
  console.log('document');
  document.dispatchEvent(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>