Skip to content

Instantly share code, notes, and snippets.

@johnsoncheg
Forked from alextaujenis/Events.js
Created March 3, 2019 06:39
Show Gist options
  • Save johnsoncheg/7773b2a18d2ec192d24c6d686b812cc1 to your computer and use it in GitHub Desktop.
Save johnsoncheg/7773b2a18d2ec192d24c6d686b812cc1 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