Subscribing to messages
We saw earlier that components can
When a message is emitted, the first argument is the name of a public method on the Magewire component.
However, not every public method can be called this way. Messages can only be emitted to methods listed in the
protected $listeners array.
If this is the case, the method will be invoked by Magewire when a component emits a message with a matching name, passing along any arguments.
Here an example of a component that listens to
A message can be emitted in several ways, depending on context.
From PHP (only during subsequent requests):
emit only works during subsequent requests.
Emitting messages with a Magewire directives:
Magento Event Interop
Every message that is emitted in Magewire is also dispatched as a Magento event.
The event name is the emit action, prefixed with
For example, the emitted message
will be automatically dispatched as the Magento event
Livewire style emit payloads
In Livewire, emit parameters are passed as individual values instead of an associative array.
The Livewire syntax can also be used in Magewire, but it is discouraged because it doesn't work well with the Magento event interoperability.
A note on coupling
One of the key advantages of the event/observer pattern (a.k.a. pub/sub or by other names) is that the publisher of the event is decoupled from any observers.
This is not the case for
emitTo, where a specific target name is specified.
Because of this,
emitTo is not an implementation of the event/observer pattern, but rather a form of message passing, more like calling a method on a specific class instance, for example
This is fine, but it is good to be mindful of the increased coupling, which can lead to more brittle code if used too much.