手写一个发布-订阅模式EventEmitter

		function EventEmitter(){
			this.message = {}
		}

		EventEmitter.prototype.on = function(type,fn){
			if(!this.message[type]){
				this.message[type] = [fn]
			}else{
				this.message[type].push(fn)
			}
		}

		EventEmitter.prototype.emit = function(type,...args){
			if(!this.message[type]) return
			this.message[type].forEach(item=>{
				item.apply(this,args)
			})
		}

		EventEmitter.prototype.remove = function(type,fn){
			if(!this.message[type]) return
			if(!fn) this.message[type] = []
			for(let i=this.message[type].length-1;i>=0;i--){
				this.message[type][i] === fn && this.message[type].splice(i,1)
			}
		}

		EventEmitter.prototype.once = function(type,fn){
			const callback = (...args) => {
				fn.apply(this,args)
				this.remove(type,callback);
			}
			this.on(type,callback)
		}

		let event = new EventEmitter()
		function age(...age){
			console.log('hello,今年我' + age)
		}
		event.on('getAge',age)
		event.emit('getAge',24) //hello,今年我24
		event.emit('getAge',25) //hello,今年我25
		event.once('getName',function(...name){ console.log('hello,' + name) })
		event.emit('getName','lisan','李三') //hello,lisan,李三
		event.emit('getName', '赵四') //空
		event.remove('getAge')

//ES6类实现
		class EventEmitter{
			constructor() {
				this.message = {}
			}
			on(type,fn){
				if(!this.message[type]){
					this.message[type] = [fn]
				}else{
					this.message[type].push(fn)
				}
			}
			emit(type,...args){
				if(!this.message[type]) return
				this.message[type].forEach((item)=>{
					item.apply(this,args)
				})
			}
			off(type,fn){
				if(!this.message[type]) return
				if(!fn) this.message[type] = []
				for(let i=this.message[type].length-1;i>=0;i--){
					this.message[type][i] == fn && this.message[type].splice(i,1)
				}
			}
			once(type,fn){
				let callback = (...args)=>{
					fn.apply(this,args)
					this.off(type,callback)
				}
				this.on(type,callback)
			}
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值