Events and Validation
Each thread dispatches comments:* events as things happen in it, such as a comment being posted, a vote changing or a request failing, and they bubble from the <verbb-comments> element. They're the place for analytics, your own validation and small changes to what's drawn. A cancellable one can stop what's about to happen with event.preventDefault().
const thread = document.querySelector('verbb-comments');
thread.addEventListener('comments:comment-created', (event) => {
analytics.track('Comment posted', {
thread: event.detail.instanceId,
waitingForApproval: event.detail.moderationState === 'pending',
});
});Listen on the element to hear one thread, or on document to hear every thread on the page. A listener added before the element starts, such as before registerCommentsWebComponents() runs, hears comments:mounted too.
Every Event
Every event's detail has these keys, along with the event's own:
apiVersion, root, instanceId, conversationUid, controller, source
apiVersion is the version of the data format the script reads. root is the thread's root element and instanceId its id, such as comments-109-1. controller is the thread's controller. source is user for the cancellable events a visitor causes, and api for everything else.
| Event | Group | Cancellable | Detail beyond the shared keys | From the thread store |
|---|---|---|---|---|
comments:mounted | Lifecycle | Nothing more | ||
comments:destroyed | Lifecycle | Nothing more | ||
comments:before-render | Lifecycle | Yes | reason, data | |
comments:before-action | Comment changes | Yes | action, commentUid | |
comments:before-submit | Editor | Yes | form, mode, commentUid, formData | |
comments:request-start | Requests | reason | Yes | |
comments:request-end | Requests | reason | Yes | |
comments:request-error | Requests | message, reason, category, code, fieldErrors, recoverable | Yes, adding error | |
comments:viewer-loaded | Lifecycle | viewer | Yes | |
comments:roots-loaded | Lifecycle | Nothing more | Yes, adding cursor, count | |
comments:replies-loaded | Lifecycle | commentUid | Yes, adding count | |
comments:sorted | Lifecycle | sort | Yes | |
comments:editor-opened | Editor | mode, commentUid | ||
comments:editor-closed | Editor | reason | ||
comments:comment-created | Comment changes | commentUid, moderationState | Yes, adding parentUid, replayed | |
comments:comment-updated | Comment changes | commentUid | Yes | |
comments:comment-deleted | Comment changes | commentUid | Yes | |
comments:comment-moderated | Comment changes | commentUid, commentId, moderationAction | Yes, adding state | |
comments:vote-changed | Comment changes | commentUid, commentId, vote | Yes | |
comments:report-changed | Comment changes | commentUid, commentId, reported | Yes | |
comments:follow-changed | Comment changes | following | Yes |
The last column shows which events the thread store in @verbb/comments-core emits too, for code without a page.
Lifecycle
comments:mounted fires when a thread starts and comments:destroyed when it stops. comments:roots-loaded fires when a page of comments has arrived and been drawn, comments:replies-loaded when a comment's replies have, with the comment's commentUid, and comments:sorted when the sort changes, with the new sort.
comments:viewer-loaded fires when the visitor's own details have arrived and been drawn, such as their votes and what they're allowed to do. Its viewer holds who's reading, with isGuest, name, isModerator, canComment and the rest, so a site can show the person in its own header.
thread.addEventListener('comments:viewer-loaded', (event) => {
const { viewer } = event.detail;
document.querySelector('#commenting-as').textContent = viewer && !viewer.isGuest
? `Commenting as ${viewer.name}`
: 'Commenting as a guest';
});comments:before-render fires before new data is drawn, and can change it or skip drawing it, as Changing Data Before It's Drawn explains.
Requests
comments:request-start and comments:request-end bracket each request, with a reason saying what it's for, such as thread, vote or create. comments:request-error fires when one fails, with a message that's safe to show a visitor, and for an error from the data API its code, category, fieldErrors and whether it's recoverable. Errors lists every code. The thread already shows the visitor what went wrong, so this event is for logging and monitoring.
thread.addEventListener('comments:request-error', (event) => {
const { reason, code, message } = event.detail;
errorTracker.captureMessage(`Comments ${reason} failed: ${code ?? 'unknown'} (${message})`);
});The Editor
comments:editor-opened fires once a form has been drawn and is ready, with the rich text editor running in it if the thread uses one, and with the cursor in it. Its mode is create, reply or edit, and commentUid names the comment being replied to or edited. comments:editor-closed fires when a reply or edit form closes, with a reason. Only one reply or edit form is open at a time, so you can find it from the thread's root, for example to keep it in view under a sticky header.
comments:before-submit fires just before a comment, reply or edit is posted, and can stop it, as Validating Before Posting explains.
Comment Changes
comments:comment-created fires once a comment or reply is posted, with its commentUid and its moderationState, which is approved, or pending when it waits for a moderator and only its author can see it. comments:comment-updated fires after an edit and comments:comment-deleted after an author deletes their own comment, each with its commentUid.
comments:vote-changed fires when a vote is made, changed or taken back, with vote as upvote, downvote or null for a vote taken back. A like is an upvote. comments:report-changed has reported, which is false once a report is withdrawn, and comments:comment-moderated has the moderator's moderationAction, such as approve or remove. These three also give commentId, the number in the comment's permalink, such as 1446 for #comment-1446. comments:follow-changed fires when someone follows or stops following the discussion, with following.
comments:before-action fires when a control with a data-comments-action attribute is clicked, with its action, such as reply, edit, delete or vote, and the commentUid it acts on. Calling event.preventDefault() stops it, for example to send people to sign in on your own page before they can reply.
thread.addEventListener('comments:before-action', (event) => {
const { action, controller } = event.detail;
if (action === 'reply' && controller?.store.getState().viewer?.isGuest) {
event.preventDefault();
openSignInDialog();
}
});comments:before-action only covers clicks. To stop a comment being posted, use comments:before-submit, because a submit listener of your own runs after the thread has already sent the comment.
Validating Before Posting
comments:before-submit fires when someone presses Post, or presses ⌘↵ or Ctrl+↵, once the thread's own checks have passed and before anything is sent. It's the one place for checks of your own, such as a minimum length or a word you don't want posted, and it can show its message in the form exactly as the server's errors appear.
thread.addEventListener('comments:before-submit', (event) => {
const { form, formData, controller } = event.detail;
if (String(formData.get('content') ?? '').trim().length >= 20) return;
event.preventDefault();
controller?.showFormErrors(form, { fieldErrors: { content: ['Please write at least 20 characters.'] } });
});A short comment isn't sent. “Please write at least 20 characters.” appears under the comment box, styled and announced to screen readers like the server's own errors, and the cursor goes back to the box with the comment still in it. The error clears when the comment is next posted.
What the Event Gives You
| Key | What it is |
|---|---|
form | The form being posted. |
mode | create, reply or edit. |
commentUid | The comment being replied to or edited, or null for a new comment. |
formData | The values about to be posted. |
In formData, the comment is content, a guest's details are guest[name] and guest[email], and a custom field is fields[handle], such as fields[rating]. formData is for reading. To send something different, change the form's own fields in your listener, because the post is built from the form once your listener has finished.
Showing Errors
controller.showFormErrors(form, errors) shows errors on a form the same way the script shows the server's, and moves the cursor to the first. fieldErrors holds messages keyed by field, using the keys the data API uses:
| Key | Shown beside |
|---|---|
content | The comment box |
guest.name and guest.email | A guest's details |
fields.handle, such as fields.rating | A custom field |
Each field shows its first message. message is shown at the top of the form when none of the field errors has a field to go beside. controller.clearFormErrors(form) removes the errors shown on a form, whether they came from the server or from showFormErrors().
// A "rating" field that must be given on top-level comments.
thread.addEventListener('comments:before-submit', (event) => {
const { form, formData, mode, controller } = event.detail;
if (mode === 'create' && !formData.get('fields[rating]')) {
event.preventDefault();
controller?.showFormErrors(form, { fieldErrors: { 'fields.rating': ['Choose a rating.'] } });
}
});The Server Has the Final Say
Checks in the browser are a convenience for visitors, and anyone can skip them by posting to the data API directly. Comments validates everything again when it arrives, including the length limit, required fields and spam protection. A rule that matters, rather than one that saves the visitor a round trip, belongs on the server too, in a listener for the plugin's beforeSave event, so it also holds for comments posted through GraphQL or your own forms. A refused post from the server shows its errors in the same places, through the same fieldErrors keys.
Changing Data Before It's Drawn
comments:before-render fires each time new data is about to be drawn, with the thread's state in event.detail.data. A listener can change that state in place, and the thread draws what it's left with. It suits small adjustments that don't justify a part override, such as renaming a badge on one page.
// The Staff badge reads Team in this thread, including on comments that load later.
thread.addEventListener('comments:before-render', (event) => {
for (const comment of Object.values(event.detail.data.comments)) {
for (const badge of comment.author?.badges ?? []) {
if (badge.type === 'staff') badge.label = 'Team';
}
}
});What the Event Gives You
detail.reason says what just changed.
reason | What arrived |
|---|---|
thread | The thread's first page, or the whole thread after a sort or a refresh |
page | Another page of comments, from Load more |
replies | A comment's replies |
viewer | The visitor's own details, such as their votes and what they may do |
comment | One comment and its parents, loaded for a link to it |
write | The answer to something the visitor did, such as a new comment, an edit or a vote |
detail.data is the thread's state from its store, with comments keyed by UID, roots for the order of the top-level comments, replies for each comment's replies, viewer for who's reading, permissions for what they may do with each comment, and labels for the thread's wording. Change what you need in place. Each comment is in the data API's shape, with its author, content, display for its formatted dates, fields for its shown custom field values and custom for anything your site adds on the server.
Calling event.preventDefault() skips drawing this update, and the thread draws again with the next one. That's rarely what you want for anything but a short pause, such as holding a redraw while your own animation finishes.
Data from the Server
The state is shared with everything else on the page that reads the thread, such as a part override or your own code reading controller.store, so a change you make here is what they see too. A change that every visitor should see is usually better made on the server, where it's cached with the thread. The plugin's Api::EVENT_DEFINE_COMMENT_DATA event adds your own data to each comment's custom object, and Comments::EVENT_DEFINE_BADGES adds badges such as “Verified buyer”, which the thread shows with no change in the browser. The plugin's Events page covers both, and the Add Your Own Data to Comments user guide adds data on the server and draws it with a part override. Data added on the server is public and cached with the thread, so it must never depend on who's looking.