Last active
December 21, 2018 04:40
-
-
Save stiekel/43264ef03160cd2a709d5903dde58917 to your computer and use it in GitHub Desktop.
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
function Bus () { | |
this.events = {} | |
this.on = async (eventName, handler) => { | |
if (!this.events[eventName]) { | |
this.events[eventName] = [] | |
} | |
let targetHandler = handler | |
let before = [] | |
if (typeof handler === 'function') { | |
position = this.events[eventName].length | |
} else if (handler.before instanceof Array) { | |
// 找到 before 中最先前的 idx | |
let position = this.events.length | |
targetHandler = handler.fn | |
before = handler.before | |
handler.before.map(bf => { | |
for (let i in this.events[eventName]) { | |
if (this.events[eventName].name === bf) { | |
if (position > i) { | |
position = i | |
} | |
} | |
} | |
}) | |
} | |
this.events[eventName].splice(position, 0, { | |
handler: targetHandler, | |
before: [], | |
stack: [] | |
}) | |
return this.events[eventName][position].stack | |
} | |
const executer = async (fn, args, en) => { | |
await fn(...args) | |
return 'in ' + en | |
} | |
this.trigger = async function (eventName, ...args) { | |
if (this.events[eventName] && this.events[eventName] instanceof Array) { | |
for (let i in this.events[eventName]) { | |
let listener = this.events[eventName][i] | |
let r = await executer(listener.handler, args, eventName) | |
console.log('===caller', arguments.caller) | |
listener.stack.push(r) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment