实现EventBus的四种方法:on、once、emit、delete

  1. // 构造EventBus
  2. function EventBusClass() {
  3. this.msgQueues = {}
  4. }
  5. EventBusClass.prototype = {
  6. // 将消息保存到当前的消息队列中
  7. on: function(msgName, func) {
  8. if (this.msgQueues.hasOwnProperty(msgName)) {
  9. if (typeof this.msgQueues[msgName] === 'function') {
  10. this.msgQueues[msgName] = [this.msgQueues[msgName], func]
  11. } else {
  12. this.msgQueues[msgName] = [...this.msgQueues[msgName], func]
  13. }
  14. } else {
  15. this.msgQueues[msgName] = func;
  16. }
  17. },
  18. // 消息队列中仅保存一个消息
  19. once: function(msgName, func) {
  20. // 无需检查msgName是否存在
  21. this.msgQueues[msgName] = func;
  22. },
  23. // 发送消息
  24. emit: function(msgName, msg) {
  25. if (!this.msgQueues.hasOwnProperty(msgName)) {
  26. return
  27. }
  28. if (typeof this.msgQueues[msgName] === 'function') {
  29. this.msgQueues[msgName](msg)
  30. } else {
  31. this.msgQueues[msgName].map((fn) => {
  32. fn(msg)
  33. })
  34. }
  35. },
  36. // 移除消息
  37. off: function(msgName) {
  38. if (!this.msgQueues.hasOwnProperty(msgName)) {
  39. return
  40. }
  41. delete this.msgQueues[msgName]
  42. }
  43. }
  44. // 将EventBus放到window对象中
  45. const EventBus = new EventBusClass()
  46. window.EventBus = EventBus
  47. function func(arg){
  48. console.log(arg);
  49. }
  50. window.EventBus.on('msgName',func);
  51. window.EventBus.emit('msgName',999);