Automatically Wire a Fragment's Custom Event to the Parent Container
When working with a fragment custom event set up to emit payload to the parent container, you can automatically wire the event to the fragment's parent container (say, a page or dynamic container), and/or its extension. Autowiring an event makes it easier to create an event listener on the parent container, without having to define an event handler in HTML.
Here's a scenario where autowiring the fragment event to its parent container is particularly useful: Suppose you have a page that contains a dynamic container, which in turn contains a fragment. When the fragment uses a custom event to pass data to the parent dynamic container, you would need to define a component event listener on the dynamic container's page (immediate parent container) to listen for the fragment event and trigger an action chain. Now suppose this extension was published and a user chose to extend this dynamic container by adding a new section, there'd be no way to invoke the event listener defined on the dynamic container's base page. Instead, the user would need to create another component event listener on the extended dynamic container page for the same logic—leading to duplicate code.
Autowiring a fragment event allows the event listener on the parent container to be invoked whenever the event is fired on the fragment. Additionally, if the event listener on the fragment's base parent container is enabled for extensions, it can be invoked even when the autowired event is fired on the extended parent container (in our example, the extended dynamic container page). If the fragment's base parent container and extended parent container both have autowired event listeners defined, both event listeners are invoked.
Here's how to autowire a fragment event create a event listener on the fragment's parent container:
- Create a custom event that emits its payload to the parent container, then enable it for autowiring on the parent container.
- In the fragment's Events tab, create a custom event that emits its payload to the parent container (Emit event to container must be selected and parameters added to specify the payload that will be passed to the parent container).
- Enter an Auto Wire Event ID, which will identify the event's listener on the parent container once created.
- Create a listener for the autowired event on the fragment's immediate parent container. If your fragment is used on a page (for example), create an event listener on the page's Event Listeners tab; if it is used in a layout's form template, create the event listener on the layout's Event Listeners tab.
- If you want the autowired event listener to be invoked when the autowired event is fired from a fragment that is part of an extended parent container, you must additionally enable the autowired event listener for extensions.