What do the args for Gutenberg subpackage “hooks” function “doAction” mean?

I suggest to take a look at the tests file to see different ways of using hooks.

They work similarly to PHP hooks, you can set several addAction and then one doAction with the name of the hook and other arguments.

The first argument of doAction has to be the action name. Then you can pass as many arguments as you want and those will pass to the addAction callback function:

const myFunction = ( arg1, arg2 ) => {
    console.log( arg1, arg2 ); // Should output 'Hello' 'Hola'
};

wp.hooks.addAction( 'action_name', 'function_name', myFunction );

wp.hooks.doAction( 'action_name', 'Hello', 'Hola' );

The first argument is the hook name. Several addAction (or addFilter) can hook into the given hook by its name and all will be executed when calling doAction (or applyFilters).
The second argument identifies the action or filter (addAction or addFilter). This is used, for example, if you want to remove one of the actions or filters. This is an adapted example taken from one of the tests:

const { addFilter, removeFilter, applyFilters } = wp.hooks;

function filterA(str) {
    return str + "A";
}

function filterB(str) {
    return str + "B";
}

function filterC(str) {
    return str + "C";
}

addFilter("test.filter", "my_callback_filter_a", filterA);
addFilter("test.filter", "my_callback_filter_b", filterB);
addFilter("test.filter", "my_callback_filter_c", filterC);

removeFilter("test.filter", "my_callback_filter_b");

console.log(applyFilters("test.filter", "test_")); // Should output test_AC

Leave a Comment