The ideal way is to have dependencies injected into your objects. Event dispatcher is registered with the global service container so you can fetch it when registering your component services in provider.php
. However, there isn't a good way to pass it down to MVC elements without a custom MVC factory. Core components don't use anything like that yet.
That said, if you just want to get your code working, you can trigger the event through the application:
$res = Joomla\CMS\Factory::getApplication()->triggerEvent('onCheckAnswer', [$post['recaptcha_response_field']]);
Note that this method is already deprecated and will be removed in 5.0. Going forward, an event object should be created and passed to dispatcher's dispatch()
method:
$dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();
$event = new Joomla\Event\Event('onCheckAnswer', [$post['recaptcha_response_field']]);
$res = $dispatcher->dispatch('onCheckAnswer', $event);