Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add custom Events to javascript objects in the browser with a Node.js style syntax
// Add custom Events to javascript objects in the browser with a Node.js style syntax
// https://gist.github.com/alextaujenis/0dc81cf4d56513657f685a22bf74893d
// Copyright 2018 Alex Taujenis
// MIT License
class Events {
constructor () {
this._callbacks = {}
}
on (key, callback) {
// create an empty array for the event key
if (this._callbacks[key] === undefined) { this._callbacks[key] = [] }
// save the callback in the array for the event key
this._callbacks[key].push(callback)
}
emit (key, ...params) {
// if the event key exists
if (this._callbacks[key] !== undefined) {
// iterate through the callbacks for the event key
for (let i=0; i<this._callbacks[key].length; i++) {
// trigger the callbacks with all provided params
this._callbacks[key][i](...params)
}
}
}
}
// EXAMPLE USAGE
// class Thing extends Events {
// constructor () {
// super()
// setInterval(() => {
// this.emit('hello', 'world')
// }, 1000)
// }
// }
// const thing = new Thing()
// thing.on('hello', (data) => {
// console.log(`hello ${data}`)
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment