Events
Detailed Description
EventWatcher is the base class for all widgets, it provides a mechanism for emitting and handling events within an application.
The event watcher allows developers to register a callback function to be bound to named events using the bind() function. The emit() function is used to trigger an event. When the event watcher emits an event, all of the callback functions bound to that specific event are called synchronously.
The following example shows a simple event watcher with a single callback function.
const watcher = new EventWatcher();
watcher.bind('event', (): void => {
console.log('Function is called!');
});
watcher.emit('event');
The results are as follows:
Function is called!
If you register multiple callback functions to be bound to one named event, only the last callback function will be triggered when the event watcher emits this event.
const watcher = new EventWatcher();
watcher.bind('event', (): void => {
console.log('Function A is called!');
});
watcher.bind('event', (): void => {
console.log('Function B is called!');
});
watcher.emit('event');
The results are as follows:
Function B is called!
The emit() function allows an arbitrary set of arguments to be passed to the callback function.
const watcher = new EventWatcher();
watcher.bind('event', (a: number, b: number): void => {
console.log('a: ', a);
console.log('b: ', b);
});
watcher.emit('event', 1, 2);
The results are as follows:
a: 1
b: 2
Removes the specified watcher for the named event with the unbind() function. All callback functions bound to named event will not be triggered.
...
watcher.unbind('event');
You can block the event watcher by setting the blocked property, meaning that emitting an event will not trigger any callback functions that are bound to it.
...
watcher.blocked = true;
watcher.emit('event'); // No callback functions are triggered.
watcher.blocked = false;