1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- /**
- * 事件委托函数封装
- * @param {*} el
- * @param {*} type
- * @param {*} fn
- * @param {*} selector
- */
- function addEventListener(el,type,fn,selector){
- if(typeof el === 'string'){
- el = document.querySelector(el)
- }
- if(!selector){
- el.addEventListener(type,fn)
- }else{
- //事件委托
- el.addEventListener(type,function(e){
- //获取点击事件源
- const target = e.target
- if(target.matches(selector)){
- fn.call(target,e)
- }
- })
- }
- }
- /**
- * 手写事件总线 -- 一个事件绑定多个回调
- */
- const eventBus = {
- //保存类型和回调的容器
- callbacks:{}
- }
- //注册事件
- eventBus.on = function(type,callback){
- if(this.callbacks[type]){
- this.callbacks[type].push(callback)
- }else{
- this.callbacks[type] = [callback]
- }
- }
- //触发事件
- eventBus.emit = function(type,data){
- if(this.callbacks[type] && this.callbacks[type].length > 0){
- this.callbacks[type].forEach(callback => {
- callback(data)
- });
- }
- }
- //注销事件
- eventBus.off = function(eventName){
- if(eventName){
- delete this.callbacks[eventName]
- }else{
- this.callbacks[type] = {}
- }
- }
|