Created
January 24, 2018 19:23
-
-
Save feliperohdee/b10aabde78eaec86bfa73c8a544d2f90 to your computer and use it in GitHub Desktop.
cool events
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 filter from 'lodash/filter'; | |
import forEach from 'lodash/forEach'; | |
import isFunction from 'lodash/isFunction'; | |
import isString from 'lodash/isString'; | |
export default class Events { | |
constructor(persist) { | |
this._fns = []; | |
} | |
trigger(event, data) { | |
forEach(this._fns, fn => { | |
const canTrigger = fn._event ? (fn._event.replace(/:.*/g, '') === event) : true; | |
if (canTrigger) { | |
if (fn._once) { | |
this.off(fn); | |
} | |
fn(event, data); | |
} | |
}); | |
} | |
on(event, context, fn, once = false) { | |
if (!isString(event)) { | |
[event, context, fn] = [null, event, context]; | |
} | |
if (isFunction(context)) { | |
[context, fn] = [null, context]; | |
} | |
if (event) { | |
fn._event = event; | |
} | |
if (context) { | |
fn._context = context; | |
} | |
if (once) { | |
fn._once = once; | |
} | |
this._fns.push(fn); | |
return () => this.off(fn); | |
} | |
once(event, context, fn) { | |
return this.on(event, context, fn, true); | |
} | |
off(event, context, fn) { | |
if (!isString(event)) { | |
[event, context, fn] = [null, event, context]; | |
} | |
if (isFunction(context)) { | |
[context, fn] = [null, context]; | |
} | |
this._fns = filter(this._fns, _fn => { | |
return (event ? _fn._event !== event : false) || (context ? _fn._context !== context : false) || (fn ? _fn !== fn : false); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment