發佈訂閱模式
class Event {
constructor() {
this.clientList = {};
}
listen(key, fn) {
if (!this.clientList[key]) {
this.clientList[key] = [];
}
this.clientList[key].push(fn);
}
trigger(key, ...args) {
if (!this.clientList[key] || this.clientList[key].length === 0) {
return false;
}
this.clientList[key].forEach(fn => {
fn.apply(this, args);
});
}
remove(key, fn) {
if (!this.clientList[key] || this.clientList[key].length === 0) {
return false;
}
if (!fn) {
this.clientList[key].length = 0;
}
this.clientList[key] = this.clientList[key].filter(f => f === fn);
}
}
const DEvent = new Event();
const fn1 = function(price) {
console.log('價格= ' + price);
};
DEvent.listen('squareMeter88', fn1);
DEvent.listen('squareMeter88', function(price) {
console.log('價格1= ' + price);
});
DEvent.trigger('squareMeter88', 3000000);
DEvent.remove('squareMeter88', fn1);
DEvent.trigger('squareMeter88', 4000000);
複製代碼