Performing JavaScript actions after Action execution

After reading about Adding a custom Action and creating your first custom Action you may want know more about the get_js_actions() method that is available in the Action class.

What it does

The method is used to get the actions that should be executed by JavaScript on success of the execute() method. For example, the Activate Plugin action refreshes the available actions to ensure the newly activated plugin is no longer in the list of plugins able to be activated, but rather in the list of plugins that can be deactivated.
Another example is the Add to Cart and Empty Cart actions, these will automatically trigger a refresh of the carts in WooCommerce.

What it can do for you

There are a few default actions available by default, and also a JavaScript trigger that allows for adding your own custom functionality.

Actions available by default

Reload page

public function get_js_actions( $args = array() ) {
	return array(
		array(
			'action' => 'reload-page',
		)
	);
}

Redirect

public function get_js_actions( $args = array() ) {
	return array(
		array(
			'action' => 'redirect',
			'url' => home_url(),
		)
	);
}

Refresh actions

public function get_js_actions( $args = array() ) {
	return array(
		array(
			'action' => 'refresh-actions',
			'data' => array(
				'actions' => $this->refreshed_actions_after_action(),
			),
		)
	);
}

Reload cart
This one is specifically for the WooCommerce integration

public function get_js_actions( $args = array() ) {
	return array(
		array(
			'action' => 'reload-cart',
		),
	);
}

Custom actions

As mentioned you’ll also be able to create your own custom available and hook them into JavaScript. This can be done by listening to a event on the document

JavaScript:

document.addEventListener( 'keyboard_action/after_execution/my-custom-even-name', function(e) {
	alert('my custom event');
	console.log(e.detail); // All arguments are passed to JS in the e.detail argument.
});

PHP:

public function get_js_actions( $args = array() ) {
	return array(
		array(
			'action' => 'my-custom-event-name',
			'arg1' => 'value1',
			'arg2' => 'value2'
		),
	);
}