1. class EventEmitter {
    2. constructor() {
    3. this.subs = {}
    4. }
    5. on(event, cb) {
    6. (this.subs[event] || (this.subs[event] = [])).push(cb)
    7. }
    8. // 也可以使用 call 指定 context
    9. trigger(event, ...args) {
    10. this.subs[event] && this.subs[event].forEach(cb => {
    11. cb(...args)
    12. })
    13. }
    14. once(event, onceCb) {
    15. const cb = (...args) => {
    16. onceCb(...args)
    17. this.off(event, onceCb)
    18. }
    19. this.on(event,cb)
    20. }
    21. off(event, offCb) {
    22. if (this.subs[event]) {
    23. let index = this.subs[event].findIndex(cb => cb === offCb)
    24. this.subs[event].splice(index, 1)
    25. if (!this.subs[event].length) delete this.subs[event]
    26. }
    27. }
    28. }
    29. let dep = new EventEmitter()
    30. let cb = function () {
    31. console.log('handleClick')
    32. }
    33. let cb2 = function () {
    34. console.log('handleMouseover')
    35. }
    36. console.group()
    37. dep.on('click', cb)
    38. dep.on('click',cb2)
    39. dep.trigger('click')
    40. console.groupEnd()
    41. console.group()
    42. dep.off('click', cb)
    43. dep.trigger('click')
    44. console.groupEnd()
    45. console.group()
    46. dep.once('mouseover', cb2)
    47. dep.trigger('mouseover')
    48. dep.trigger('mouseover')
    49. console.groupEnd()