EventBus.js 823 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. class EventBus{
  2. constructor(){
  3. this.task = {}
  4. }
  5. on(name, cb){
  6. if(!this.task[name]){
  7. this.task[name] = []
  8. }
  9. typeof cb === 'function' && this.task[name].push(cb)
  10. }
  11. emit(name, ...arg){
  12. let taskQueen = this.task[name]
  13. if(taskQueen && taskQueen.length > 0){
  14. taskQueen.forEach(cb=>{
  15. cb(...arg)
  16. })
  17. }
  18. }
  19. off(name, cb){
  20. let taskQueen = this.task[name]
  21. if(taskQueen && taskQueen.length > 0){
  22. let index = taskQueen.indexOf(cb)
  23. index != -1 && taskQueen.splice(index, 1)
  24. }
  25. }
  26. once(name, cb){
  27. function callback(...arg){
  28. this.off(name, cb)
  29. cb(...arg)
  30. }
  31. typeof cb === 'function' && this.on(name, callback)
  32. }
  33. }
  34. export default EventBus