Skip to content

Instantly share code, notes, and snippets.

@okovalov
Last active July 13, 2020 16:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save okovalov/88f5369dc266a8276887d9790a5c9308 to your computer and use it in GitHub Desktop.
How to use cusrtom events
// In JavaScript we can create custom events, and the way it works changes in the
// browser and in Node.js.
// In the frontend we use the Event object which is provided by the browser:
const anEvent = new Event('start');
// You can trigger the event using
document.dispatchEvent(anEvent)
// and when this happens, the event listener is triggered:
document.addEventListener('start', event => {
console.log('started!')
})
// You can send custom data using the CustomEvent built-in object instead of Event,
// which accepts an object as the second parameter:
const anotherEvent = new CustomEvent('start', {
detail: {
color: 'white'
}
})
// Using CustomEvent, in the event listener you can ask the data
// to the event object using event.detail (you can’t use another property):
document.addEventListener('start', event => {
console.log('started!')
console.log(event.detail)
})
// On the backend side, Node offers us the option to build a similar system
// using the events module.
// This module, in particular, offers the EventEmitter class, which we’ll use
// to handle our events.
// You initialize that using
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
// For example, let’s create a start event, and as a matter of providing
// a sample, we react to that by just logging to the console:
eventEmitter.on('start', () => {
console.log('started')
})
// When we run
eventEmitter.emit('start')
// the event handler function is triggered, and we get the console log.
// You can pass arguments to the event handler by passing them as additional
// arguments to emit():
eventEmitter.on('start', (number) => {
console.log(`started ${number}`)
})
eventEmitter.emit('start', 23)
// Multiple arguments:
eventEmitter.on('start', (start, end) => {
console.log(`started from ${start} to ${end}`)
})
eventEmitter.emit('start', 1, 100)
// from https://flaviocopes.com/javascript-custom-events/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment