Skip to content

Instantly share code, notes, and snippets.

@alextaujenis
Last active March 3, 2019 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alextaujenis/0dc81cf4d56513657f685a22bf74893d to your computer and use it in GitHub Desktop.
Save alextaujenis/0dc81cf4d56513657f685a22bf74893d to your computer and use it in GitHub Desktop.
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