Events and Listeners
The ToughClicks JavaScript library provides an event system that allows your application to respond to validation state changes, successful acceptances, and internal errors. This enables you to build responsive user interfaces and handle the acceptance workflow appropriately.
Overview
ToughClicks fires events at key moments during the acceptance lifecycle. By listening to these events, you can:
- Enable or disable form controls based on validation state
- Navigate users after successful acceptance
- Handle errors gracefully
- Integrate acceptance flow with your application logic
Registering Event Listeners
Use the on() method to register event listeners. You can register as many listeners as needed for each event type.
Syntax:
TC.on(eventType, callbackFunction);
Example:
function myValidHandler(e) {
console.log('Validation state changed:', e.detail.isValid);
}
function myAcceptedHandler(e) {
console.log('Documents accepted:', e.detail);
}
TC.on('tc-valid', myValidHandler);
TC.on('tc-accepted', myAcceptedHandler);
Event Types
tc-valid
Fires when the validation state of ToughClicks changes. This event indicates whether all requirements are met for acceptance to proceed.
Event detail:
{
isValid: boolean // true when checkboxes are checked and valid user identifier is set
}
When it fires:
- User checks or unchecks agreement checkboxes
- User enters or modifies their identifier
- Display method changes validation state (e.g., scroll reaches bottom)
Use cases:
- Enable/disable submit buttons
- Show validation messages
- Update UI to reflect readiness state
Example:
TC.on('tc-valid', (e) => {
const submitButton = document.getElementById('btn-submit');
if (e.detail.isValid) {
submitButton.disabled = false;
submitButton.classList.add('enabled');
} else {
submitButton.disabled = true;
submitButton.classList.remove('enabled');
}
});
Important: Once the tc-valid event fires with isValid: true, it is safe to call TC.accept() if you're using manual acceptance mode.
tc-accepted
Fires after all documents have been fully executed and immutable records have been stored in the ToughClicks acceptance database.
Event detail:
{
allAccepted: boolean // true if all documents were successfully accepted
}
When it fires:
- All acceptance records have been created successfully
- Automatic acceptance completes (when
manualAcceptance: false) - Manual acceptance completes (after calling
TC.accept())
Use cases:
- Redirect users to the next page
- Show success messages
- Submit forms
- Trigger application workflows
Example:
TC.on('tc-accepted', (e) => {
if (e.detail.allAccepted) {
// Show success message
showNotification('Terms accepted successfully!', 'success');
// Redirect after a brief delay
setTimeout(() => {
window.location.href = '/dashboard';
}, 1500);
} else {
// Handle partial acceptance scenario
showNotification('Some terms could not be accepted. Please try again.', 'error');
}
});
Important: Wait for this event before allowing the signer to proceed. Continuing before tc-accepted fires may result in incomplete acceptance records.
tc-internal-error
Fires when the library experiences an internal error. This allows you to handle errors gracefully and provide appropriate feedback to users.
Event detail:
{
error: Error // Error object with details
}
When it fires:
- Network request failures
- API errors
- Unexpected internal library errors
Use cases:
- Display error messages to users
- Log errors for monitoring
- Implement fail-open or fail-closed logic
- Retry logic
Example:
TC.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Show user-friendly error message
showNotification(
'We encountered an issue processing your agreement. Please try again later.',
'error'
);
// Log to error tracking service
errorTracker.log({
message: 'ToughClicks internal error',
error: e.detail.error,
userId: currentUser.id
});
// Optionally implement fail-open logic
// (see Error Handling section below)
});
See Error Handling for detailed information about handling errors.
Complete Working Example
Here's a comprehensive example showing all three events working together:
const { ToughClicks } = window.ToughClicks;
const tc = new ToughClicks(clientToken, packetId);
// Configure display options with manual acceptance
const options = {
containerId: 'tc-container',
displayMethod: 'Individual',
signerIdSelector: 'email-input',
manualAcceptance: true
};
tc.setDisplayOptions(options);
// Track validation state
let isValid = false;
// Handle validation state changes
tc.on('tc-valid', (e) => {
isValid = e.detail.isValid;
const submitButton = document.getElementById('btn-submit');
if (isValid) {
submitButton.disabled = false;
submitButton.textContent = 'Accept Terms';
} else {
submitButton.disabled = true;
submitButton.textContent = 'Please review all terms';
}
});
// Handle successful acceptance
tc.on('tc-accepted', (e) => {
if (e.detail.allAccepted) {
console.log('All agreements executed successfully');
// Show success message
document.getElementById('success-message').style.display = 'block';
// Proceed with application flow
completeRegistration();
}
});
// Handle errors
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Show error message
document.getElementById('error-message').style.display = 'block';
document.getElementById('error-message').textContent =
'Unable to process acceptance. Please contact support.';
// Re-enable form for retry
document.getElementById('btn-submit').disabled = false;
});
// Manual acceptance on button click
document.getElementById('btn-submit').addEventListener('click', async () => {
if (!isValid) return;
// Disable button during processing
const button = document.getElementById('btn-submit');
button.disabled = true;
button.textContent = 'Processing...';
try {
const success = await tc.accept();
if (!success) {
// Handle failure
button.disabled = false;
button.textContent = 'Accept Terms';
alert('Failed to accept terms. Please try again.');
}
// Success is handled by tc-accepted event
} catch (error) {
// Handle exception
button.disabled = false;
button.textContent = 'Accept Terms';
console.error('Exception during acceptance:', error);
}
});
Event Listener Best Practices
Multiple Listeners
You can register multiple listeners for the same event:
// Analytics tracking
TC.on('tc-accepted', (e) => {
analytics.track('Terms Accepted', {
packetId: packetId,
timestamp: new Date().toISOString()
});
});
// UI updates
TC.on('tc-accepted', (e) => {
showSuccessMessage();
});
// Navigation
TC.on('tc-accepted', (e) => {
setTimeout(() => window.location.href = '/next-page', 2000);
});
Error Handling in Listeners
Wrap listener code in try-catch blocks to prevent errors from breaking the acceptance flow:
TC.on('tc-accepted', (e) => {
try {
// Your code
analytics.track('acceptance', e.detail);
} catch (error) {
console.error('Error in tc-accepted handler:', error);
// Don't let analytics errors break the flow
}
});
Related Documentation
- Manual Acceptance - Control when acceptances are created
- Error Handling - Detailed error handling strategies
- Display Options - Configure the acceptance flow