手写发布订阅

Rinsann 2022年05月06日 422次浏览

const eventHub = {
	map: {},
	on: (name, fn) => {
		// 入队 
		// 防御性编程
		eventHub.map[name] = eventHub.map[name] || []
		eventHub.map[name].push(fn)
	},
	emit: (name, data) => {
		const q = eventHub.map[name]
		if (!q) return
		q.map(f => f.call(undefined, data))
		return undefined
	}, // trigger
	off: (name, fn) => {
		const q = eventHub.map[name]
		if (!q) {return}
		const index = q.indexOf(fn)
		if (index < 0) {return}
		q.splice(index, 1)
	}
}

eventHub.on('click',console.log)
eventHub.off('click',console.log)
eventHub.on('click', console.error)

setTimeout(() => {
	eventHub.emit('click', 'rick')
}, 3000)

class 写法

// Class 实现
class EventHub {
	map = {}
	
	on(name, fn) {
		this.map[name] = this.map[name] || []
		this.map[name].push(fn)
	}
	
	emit(name, data) {
		const fnList = this.map[name] || []
		fnList.forEach(fn => fn.call(undefined, data))
	}
	
	off(name, fn) {
		const fnList = this.map[name] || []
		const index = fnList.indexOf(fn)
		if (index < 0) return
		fnList.splice(index, 1)
	}
}

// 使用方法
const e = new EventHub()
e.on('click', (name) => {
	console.log('hi' + name)
})

e.on('click', (name) => {
	console.log('hello' + name)
})

setTimeout(() => {
	e.emit('click', 'rick')
}, 3000)