1. 程式人生 > 實用技巧 >面向物件開發之自定義事件

面向物件開發之自定義事件

class Event {
  constructor(){
    this.handlers = {}; // 記錄所有的事件及處理函式
    // {
    //   click: [fn1, fn2],
    //   mouseover: [fn3, fn4],
    // };
    
  }

  /**
   * on 新增事件監聽
   * @param type    要新增的事件型別
   * @param handler 要新增的的事件處理函式
   * @param once    是否只執行一次
   */
  on(type, handler, once = false) {
    
if (!this.handlers[type]) { this.handlers[type] = []; } if (this.handlers[type].includes(handler)) { this.handlers[type].push(handler); handlers.once = once; } } /** * off取消事件監聽 * @param type 要取消的事件型別 * @param handler 要取消的事件處理函式,如果不傳則清除該型別所有函式 */ off(type, handler) {
if (this.handlers[type]) { if (handler === undefined) { this.handlers[type] = []; } else { this.handlers[type] = this.handlers[type].filter(f => f !== handler) } } } /** * once 該函式只執行一次 * @param type 要新增的事件型別 * @param handler 要新增的的事件處理函式 */ once() {
this.on(type, handler, true); } /** * trigger 執行該函式 * @param type 要執行的函式型別 * @param eventData 事件物件 * @param point this執行 */ trigger(type, eventData = {}, point = this) { if (this.handlers[type]) { this.handlers[type].forEach((f) => { f.call(point, eventData); if (f.once) { this.off(type, f); } }) } } }
let el = new Event();
el.on('click', fn);
function fn() {
  console.log('11');    
}