Skip to content

Instantly share code, notes, and snippets.

@ooflorent
Created December 3, 2014 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ooflorent/a695a4099860036f5190 to your computer and use it in GitHub Desktop.
Save ooflorent/a695a4099860036f5190 to your computer and use it in GitHub Desktop.
Simple ES6 emitter
class Listener {
constructor(fn, ctx) {
this.fn = fn
this.ctx = ctx
}
}
class Emitter {
listen(fn, ctx) {
this.listeners.push(new Listener(fn, ctx))
}
unlisten(fn, ctx) {
for (var i = 0; i < this.listeners.length; i++) {
var listener = this.listeners[i]
if (listener.fn === fn && listener.ctx === ctx) {
this.listeners.splice(i, 1)
return
}
}
}
emit() {
for (var i = 0; i < this.listeners.length; i++) {
this.listeners[i].fn.apply(this.listeners[i].ctx, arguments)
}
}
}
export function emitter() {
function action() {
action.emit.apply(action, arguments)
}
action.listeners = []
action.__proto__ = Emitter.prototype
return action
}
import {emitter} from './emitter'
let e = emitter()
e.listen(a => console.log(a))
e.listen(a => console.log(a * 2))
e(2) // 2, 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment