Open wang1dot0 opened 4 years ago
观察者模式
发布订阅模式
class SubPub { constructor() { this.handlers = {}; } on(event, handler) { if (!this.handlers.hasOwnproperty(event)) { this.handlers[event] = []; } if (typeof handler !== 'function') { throw new Error('handler must be a function.'); } this.handlers[event].push(handler); return this; } emit(event, ...args) { if(!this.handlers.hasOwnproperty(event)) { throw new Error('No event: ', event); } this.handlers[event].forEach(func => { func.apply(null, args); }); } off(event, handler) { if(!this.handlers.hasOwnproperty(event)) { throw new Error('No event: ', event); } if (typeof handler !== 'function') { throw new Error('handler must be a function.'); } this.handlers[event].forEach((func, idx) => { if (func === handler) { this.handlers[event].splice(idx, 1); return false; } }); } }
观察者模式
发布订阅模式