1. class EventBus {
    2. constructor () {
    3. this.event = {}
    4. }
    5. on (type, listener, ...agrs) {
    6. this.event[type] = this.event[type] || []
    7. listener.agrs = [...agrs] // 将参数放到监听函数的属性中
    8. this.event[type].push(listener)
    9. return this.off.bind(listener) // 同步绑定off函数
    10. }
    11. off (type, listener) {
    12. this.event[type] = this.event[type].filter((type) => type !== listener) // 解绑函数
    13. }
    14. fire(type, ...args) {
    15. if (this.event[type]) {
    16. this.event[type].forEach((listener) => {
    17. let allArgs = [...agrs, ...listener.agrs]
    18. listener.call(this, ...allArgs)
    19. })
    20. }
    21. }
    22. once (type, listener) {
    23. this.events[type] = this.events[type] || [];
    24. function proxyFun(...agrs) {
    25. listener.call(this, ...agrs)
    26. this.off(type, listener)
    27. }
    28. this.event[type].push(proxyFun)
    29. }
    30. }