JsAction asynchronous dispatcher example
HTML
<script id="contract" src="https://www.gstatic.com/jsaction/contract.js"></script>
<button jsaction="button.handleEvent">
click here to capture events
</button>
<hr>
<div>
Click on the button above to capture events. Even though the dispatcher has not loaded yet, these events will be queued until the dispatcher does load. In 10 seconds, the event dispather will load and automatically replay the events.
</div>
JavaScript
const eventContract = new jsaction.EventContract();
// Events will be handled for all elements under this container.
eventContract.addContainer(window.document.documentElement);
// Register the event types handled by JsAction.
eventContract.addEvent('click');
// This code will be executed after the dispatcher loads, which is done 10 seconds
// after page load to simulate late loading the dispatcher. When the dispatcher loads,
// this code will replay any event that was captured before the dispatcher was
// loaded.
const lateLoadedCode = `
// This is the actual event handler code.
function handleEvent() {
alert('event handled!');
}
// This code replays the queued events. Applications can define custom replay
// strategies.
function replayEvents(events, jsActionDispatcher) {
while (events.length) {
jsActionDispatcher.dispatch(events.shift());
}
}
// Initialize the dispatcher, register the handlers, and then replay the queued events.
const dispatcher = new jsaction.Dispatcher();
eventContract.dispatchTo(dispatcher.dispatch.bind(dispatcher));
dispatcher.registerHandlers(
'button',
null,
{ 'handleEvent': handleEvent });
dispatcher.setEventReplayer(replayEvents);
`;
// Load the dispatcher code 10 seconds after page load to simulate late loading
// the dispatcher while the contract queues events.
window.setTimeout(function() {
alert('loading dispatcher');
var script = document.createElement('script');
script.src = 'https://www.gstatic.com/jsaction/dispatcher.js';
script.async = true;
script.onload = () => eval(lateLoadedCode);
document.getElementById('contract').parentNode.appendChild(script);
}, 10000);