模拟Vue中的组件通信($on,$emit)

  1. class MyEvent {
  2. protected readonly store: { [key: string]: Function };
  3. private static instance: MyEvent;
  4. constructor() {
  5. if (!MyEvent.instance) {
  6. this.store = {}
  7. MyEvent.instance = this
  8. }
  9. return MyEvent.instance
  10. }
  11. $on(type: string, callBack: Function) {
  12. if (!this.store[type]) {
  13. this.store[type] = callBack
  14. }
  15. }
  16. $emit(type: string, data?: any) {
  17. if (!this.store[type]) {
  18. console.warn(`当前${type}没有被注册!`)
  19. } else {
  20. let fn = this.store[type]
  21. fn(data)
  22. }
  23. }
  24. $off(type: string) {
  25. delete this.store[type]
  26. }
  27. }
  28. let eve = new MyEvent()
  29. eve.$on("success",function(e){
  30. console.log(e)
  31. })
  32. eve.$emit("success",{detail:"ok"})