Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

Why does jQuery's .on() work but native JavaScript's .addEventListener() doesn't?

I need to listen to WooCommerce's custom events like wc_fragment_refresched or added_to_cart. But when creating a listener for those events via the native addEventListener nothing happens. But jQuery's .on() works fine.

Working:

jQuery(document.body).on('wc_fragments_refreshed', function() {
  console.log("hehey!");
});

Not working:

document.body.addEventListener('wc_fragments_refreshed', function() {
  console.log("hoho!");
});

Does anyone have a clue why the native listener isn't working?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The difference is because addEventListener() doesn't listen for events triggered by jQuery. For that event handler to be raised you need to use dispatchEvent on document.body.

Below is an example. Note that jQuery fires twice because it does handle both event triggers.

// jQuery
$(document.body).on('wc_fragments_refreshed', function() {
  console.log("jQuery handled the event");
}).trigger('wc_fragments_refreshed');

// Native
document.body.addEventListener('wc_fragments_refreshed', function() {
  console.log("POJS handled the event");
});
document.body.dispatchEvent(new Event('wc_fragments_refreshed'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...