Documentation for AEM is often tricky to find for certain features. So we are starting a new blog series called "Short Tips & Tricks" where we can share some of the more common solutions that are not always obvious.
Today we want to discuss cq:listeners for AEM components.
Here is a common use-case: you have an alert bar at the top of a site that relies on a JavaScript library to cycle through different messages. The alert bar is an AEM component, and unfortunately after each authoring update, the JavaScript does not function until the author manually reloads the authoring page.
Here is where the cq:listeners node comes in handy, since it defines what happens before or after an action is performed on the component.
The possible properties are:
- beforedelete: The handler is triggered before the component is removed.
- beforeedit: The handler is triggered before the component is edited.
- beforecopy: The handler is triggered before the component is copied.
- beforeinsert: The handler is triggered before the component is inserted.
- beforechildinsert: The handler is triggered before the component is inserted. Only operational for the touch-enabled UI.
- beforemove: The handler is triggered before the component is moved.
- afterdelete: The handler is triggered after the component is deleted.
- afteredit: The handler is triggered after the component is edited.
- aftercopy: The handler is triggered after the component is copied.
- afterinsert: The handler is triggered after the component is inserted.
- afterchildinsert: The handler is triggered after the component is inserted inside another component (containers only).
- aftermove: The handler is triggered after the component is moved.
And some predefined values for the above listeners are:
- REFRESH_SELF
- REFRESH_PARENT
- REFRESH_PAGE
- REFRESH_INSERTED
When we are dealing with nested components the values for aftercopy and aftermove must be REFRESH_PAGE.
The most common used properties/values in our experience are:
REFRESH_SELF: This refreshes the individual component after an action has been completed on it. This applies to components that aren't dependent on any other component.
REFRESH_PARENT: This will refresh the parent component of the one that the action has been applied to.
REFRESH_PAGE: While not used as often as the other two since this will refresh the whole page, it might be helpful in very specific cases.
Finally, here is a code example that shows how to set the cq:listener node's "afteredit" property to "REFRESH_SELF". This will cause the component to refresh after the author has made and edit. In the case of our alert bar above, this is sufficient to restore the correct JavaScript functionality after each edit.
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:EditConfig">
<cq:listeners
jcr:primaryType="cq:EditListenersConfig"
afteredit="REFRESH_SELF"/>
</jcr:root>