Test event subscriptions, DOM CustomEvents, and intercept Save/Open operations. Interact with the pivot to trigger events.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Events Example</title>
<script src="https://cdn.webpivottable.com/wpt/latest/wpt.js"></script>
</head>
<body>
<h1>Event Handling Demo</h1>
<!-- Event Log -->
<div id="log" style="background:#1e1e2e;color:#cdd6f4;padding:16px;border-radius:8px;height:200px;overflow:auto"></div>
<!-- Pivot Table -->
<web-pivot-table id="wpt" style="width:100%;height:600px"></web-pivot-table>
<script>
const wpt = document.getElementById('wpt')
const log = document.getElementById('log')
function addLog(message) {
const timestamp = new Date().toLocaleTimeString()
log.textContent += `[${timestamp}] ${message}\n`
log.scrollTop = log.scrollHeight
}
// 1. Subscribe to individual events
const unsubPivot = wpt.eventBus.on('PIVOT_CHANGED', (detail) => {
addLog('PIVOT_CHANGED: Layout updated')
})
const unsubData = wpt.eventBus.on('DATA_LOADED', (detail) => {
addLog(`DATA_LOADED: ${detail.rowCount} rows`)
})
// 2. Subscribe to all events with wildcard
const unsubAllEvents = wpt.eventBus.on('*', (eventType, detail) => {
addLog(`EVENT: ${eventType}`)
})
// 3. DOM CustomEvents (alternative approach)
wpt.addEventListener('wpt:pivot-changed', (e) => {
addLog('DOM Event: wpt:pivot-changed')
})
// 4. Intercept Save/Open operations
wpt.eventBus.on('BEFORE_SAVE', (detail) => {
addLog('Intercepting save operation...')
return false // Prevent default save dialog
})
wpt.eventBus.on('BEFORE_OPEN', (detail) => {
addLog('Intercepting open operation...')
return false
})
// 5. Error handling
wpt.eventBus.on('ERROR', (detail) => {
addLog(`ERROR: ${detail.message}`)
})
// Load initial data
wpt.setWptFromCsvUrl('https://cdn.webpivottable.com/samples/sales.csv')
addLog('Loading initial data...')
// Cleanup function (call when component unmounts)
function cleanup() {
unsubPivot()
unsubData()
unsubAllEvents()
}
</script>
</body>
</html>
eventBus.on() for internal WebPivotTable eventsaddEventListener() for CustomEvents (alternative approach)false from BEFORE_SAVE/BEFORE_OPEN to prevent default behavior'*' to catch all events (useful for debugging)