EventBus 實現

實現:

class MyEventBus{
	constructor() {
		this.eventQueue = {}
	}
	on(eventName, callback) {  //訂閱
		if (!this.eventQueue[eventName]) {
			this.eventQueue[eventName] = []
		}
		this.eventQueue[eventName].push(callback)
	}
	once(eventName, callback) {
        let wrap = (...argus) => {
            callback.apply(this, argus)
            this.off(eventName, wrap)
        }
        this.on(eventName,wrap)
	}
	emit(eventName, ...argus) {  //發佈
       if(this.eventQueue[eventName]) {
	        for(let callback of this.eventQueue[eventName]){
	             callback(...argus);
	     	}       	
	     }
	}
	off(eventName, callback) {
        let cbList = this.eventQueue[eventName];
		if(cbList) {
            if(callback) {
                cbList.forEach((item, index) => {
                    if (item == callback) cbList.splice(index, 1)
                })
            } else {
                cbList.length = 0;
            }
		}
	}
}

測試

const EventBus = new MyEventBus()

//訂閱消息
EventBus.once('first-event', function(msg) {
    alert(`訂閱的消息是:${msg}`);
});

// 發送消息
EventBus.emit('first-event', "123")
EventBus.emit('first-event', "456")

// 移除消息
EventBus.off('first-event')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章