Last active
June 19, 2019 03:59
-
-
Save jsonleex/5a5fdc48686a6324cf428f1f65ac0576 to your computer and use it in GitHub Desktop.
[发布-订阅模式] #Javascript #设计模式
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
export default class OnFire { | |
constructor() { | |
this.es = {}; | |
} | |
on(evt, cb, once = false) { | |
if (!this.es[evt]) { | |
this.es[evt] = []; | |
} | |
this.es[evt].push({ cb, once }); | |
} | |
once(evt, cb) { | |
this.on(evt, cb, true); | |
} | |
off(evt, cb) { | |
// 清空 | |
if (evt === undefined) { | |
this.es = {}; | |
return; | |
} | |
if (cb === undefined) { | |
delete this.es[evt]; | |
return; | |
} | |
const ls = this.es[evt] || []; | |
ls.splice(ls.findIndex(l => l.cb === cb), 1); | |
} | |
fire(evt, ...args) { | |
const ls = this.es[evt] || []; | |
let j = ls.length; | |
for (let i = 0; i < j; i++) { | |
const { cb, once } = ls[i]; | |
cb.apply(this, args); | |
once && this.off(evt, cb); | |
} | |
} | |
// cname of fire | |
emit(evt, ...args) { | |
this.fire(evt, ...args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment