2

I have the following code that triggers whenever the cart is updated. The problem is that the jQuery version works as expected but the Vanilla JS doesn't.

jQuery( document.body ).on('updated_cart_totals', function( event ) {
    console.log( 'in here' ); // Works.
} );

document.body.addEventListener( 'updated_cart_totals', function( event ) {
    console.log( 'in here too' ); // Doesn't work.
} );

Is there something I am missing?

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • Does this answer your question? [Listen for jQuery Event With Vanilla JS](https://stackoverflow.com/questions/40915156/listen-for-jquery-event-with-vanilla-js) – David Buck Oct 20 '20 at 18:12

2 Answers2

1

It appears to be answered before https://stackoverflow.com/a/41727891/5454218

jQuery uses its own system of event/data binding which inter-operates only one way. In WooCommerce context it's an essential part of its system, so don't shy away from it. No shame in using jQuery when you're already deep in this pile of s**t.

  • Hi, if the question was answered before, please mark the question as a duplicate. Or write the link in the comments. [From review](https://stackoverflow.com/review/first-posts/27432558) – Pablochaches Oct 21 '20 at 01:12
0

My Answer would be, Yes it's now possible to detect by addAction() and doAction() using Vanilla JS -

  1. wp.hooks.addAction().
  2. wp.hooks.doAction()

How to do - My Approach

// Trigger any jQuery event
$document.trigger( 'test-trigger', [data] );

// Fire action
wp.hooks.doAction( 'test.trigger', data );

// Catch this event from anywhere in JS
wp.hooks.addAction( 'test.trigger', 'cp/test-trigger', function(data) {
    console.log('JS Response data', data);
} , 10);

Reference Example of WordPress Core

For reference, Let's see a WordPress heartbeat js's doAction() - https://github.com/WordPress/wordpress-develop/blob/trunk/src/js/_enqueues/wp/heartbeat.js#L460

// heartbeat.js#L460
$document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
wp.hooks.doAction( 'heartbeat.tick', response, textStatus, jqXHR );

// Catch that heartbeat tick from anywhere in JS
wp.hooks.addAction( 'heartbeat.tick', 'cp/heartbeat-tick', function(response, textStatus, jqXHR) {
    console.log('heartbeat response', response);
} , 10, 3);
Maniruzzaman Akash
  • 4,610
  • 1
  • 37
  • 34