2

The package is supposed to mime WP's own actions system:

https://github.com/WordPress/gutenberg/tree/master/packages/hooks

I've installed it locally and loaded up all of its modules, unfortunately, I seriously don't understand what the functionName and callback are in the case of addAction.

I tried messing with it quite a bit but no success. I thought functionName is the function I'm hooking to an action, for example:

var actions_api = createHooks();
function testFunction( a ) {
    console.log(a);
}
actions_api.addAction( 'testHook', 'global', 'testFunction', function( a ) {
    console.log(a);
}, 10 );
actions_api.doAction( 'testHook', 'super_arg' );

Returns the error The hook callback must be a function., while the code above seems stupid, I tried to mess with it a bit but no success.

What am I missing? In theory, there shouldn't be a need for a callback for an action.

3

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
  • 2
    +1 for suggesting looking at tests files. The tests files in general are often "forgotten" documentation :-) – birgire Jan 18 at 20:38
  • That's exactly my trouble here! What could that function_name be? – coolpasta Jan 19 at 12:19
  • @coolpasta I just figured out about it looking at tests. Please check the updated answer. – Alvaro Jan 19 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.