You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionnoop(){}functionisFunction(cb){returnObject.prototype.toString.call(cb)==='[object Function]'}functionisArray(v){returnObject.prototype.toString.call(cb)==='[object Array]'}classEventBus{constructor(){this._event=newMap()}_isFunction(cb){returnObject.prototype.toString.call(cb)==='[object Function]'}// 可注册多个事件,允许相同,且事件遵循先进先出原则on(eventName='',callback=noop){if(!eventName)returnthisif(callback&&!isFunction(callback)){throwError(`${callback} is not a function`)}constfns=this._event.get(eventName)||[]this._event.set(eventName,[...fns,callback])returnthis}// 事件仅能注册一次,且仅执行一次,执行完后自动移除事件once(eventName='',callback=noop){if(this._event.has(eventName))returnthisif(callback&&!isFunction(callback)){throwError(`${callback} is not a function`)}this._event.set(eventName,callback)returnthis}// 事件触发emit(eventName='', ...args){constfns=this._event.get(eventName)if(!fns)returnthisif(!isArray(fns)){fns.apply(this,args)this._event.delete(eventName)// 执行完后移除事件returnthis}for(constfnoffns){fn.apply(this,args)// 确保方法执行时的this指向没有问题}returnthis}off(eventName='',callback){constfns=this._event.get(eventName)if(!fns)returnthisif(callback&&!isFunction(callback)){throwError(`${callback} is not a function`)}constfilterFns=fns.filter(fn=>fn!==callback)if(!filterFns.length){this._event.delete(eventName)}else{this._event.set(eventName,filterFns)}returnthis}}constev=newEventBus()console.log('_isFunction---',ev._isFunction(function(){}))constvfn=function(){console.log('v---vvv---',this)}conste1=ev.on('testv',function(){console.log('testv---|||-',arguments,this)}).on('vvv',vfn)// ev.on('testv', '6454')ev.once('testv',function(){console.log('testv-2222-++++---',arguments)})ev.emit('testv',1,2,3)console.log('e----',e1)ev.emit('vvv')setTimeout(()=>{ev.emit('testv',5)ev.off('vvv',vfn)},1000)setTimeout(()=>{// ev.off('testv', function)ev.emit('vvv')ev.emit('testv','fffff')},1500)
The text was updated successfully, but these errors were encountered:
on(eventName, func)
: 可注册多个事件,允许相同,且事件遵循先进先出原则,监听 eventName事件, 事件触发的时候调用 func函数once(eventName, func)
: 事件仅能注册一次,且仅执行一次,执行完后自动移除事件emit(eventName, arg1, arg2, arg3,arg4...)
: 触发eventName 事件, 并且把参数 arg1, arg2, arg3,arg4...传给事件处理函数off(eventName, func)
: 停止监听某个事件,根据func的引用是否匹配来移除对应事件的监听The text was updated successfully, but these errors were encountered: