發佈訂閱模式又稱觀察者模式bash
// 發佈訂閱模式
const eventSubscribe = (function() {
const eventSet = {};
return {
// 獲取訂閱列表
getEventList: () => Object.keys(eventSet),
// 得到某個key的callbacklist
getCallbacks: (key) => eventSet[key],
// 訂閱
subscribe: (key, ...callbacks) => {
if (!eventSet[key]) {
eventSet[key] = [];
}
eventSet[key].push(...callbacks);
},
// 發佈函數
publish: (key, ...args) => {
const callbacks = this.getCallbacks(key);
if(callbacks && callback.length === 0) {
return false;
}
for (const callback of callbacks) {
callback.apply(this, args);
}
},
// 刪除訂閱
remove: (key, callback) => {
const callbacks = this.getCallbacks(key);
if (callbacks && callbacks.length === 0) {
return false;
}
if (!callback) { // 無callback ,取消key的全部回調
callbacks && (callbacks.length = 0);
}
callbacks = callbacks.filter((item) => item !== callback);
return true;
}
};
})();
複製代碼