Last active
March 3, 2019 06:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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