index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * 事件委托函数封装
  3. * @param {*} el
  4. * @param {*} type
  5. * @param {*} fn
  6. * @param {*} selector
  7. */
  8. function addEventListener(el,type,fn,selector){
  9. if(typeof el === 'string'){
  10. el = document.querySelector(el)
  11. }
  12. if(!selector){
  13. el.addEventListener(type,fn)
  14. }else{
  15. //事件委托
  16. el.addEventListener(type,function(e){
  17. //获取点击事件源
  18. const target = e.target
  19. if(target.matches(selector)){
  20. fn.call(target,e)
  21. }
  22. })
  23. }
  24. }
  25. /**
  26. * 手写事件总线 -- 一个事件绑定多个回调
  27. */
  28. const eventBus = {
  29. //保存类型和回调的容器
  30. callbacks:{}
  31. }
  32. //注册事件
  33. eventBus.on = function(type,callback){
  34. if(this.callbacks[type]){
  35. this.callbacks[type].push(callback)
  36. }else{
  37. this.callbacks[type] = [callback]
  38. }
  39. }
  40. //触发事件
  41. eventBus.emit = function(type,data){
  42. if(this.callbacks[type] && this.callbacks[type].length > 0){
  43. this.callbacks[type].forEach(callback => {
  44. callback(data)
  45. });
  46. }
  47. }
  48. //注销事件
  49. eventBus.off = function(eventName){
  50. if(eventName){
  51. delete this.callbacks[eventName]
  52. }else{
  53. this.callbacks[type] = {}
  54. }
  55. }