Created
December 3, 2014 10:11
-
-
Save ooflorent/a695a4099860036f5190 to your computer and use it in GitHub Desktop.
Simple ES6 emitter
This file contains 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
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 | |
} |
This file contains 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
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