WooCommerce JS event doesn't work using Vanilla JS but works fine with jQuery

Viewed 709

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?

2 Answers

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.

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);
Related