DIV CSS 佈局教程網

用自訂事件解耦前端邏輯:從 keypress 綁定到 EventEmitter
編輯:JavaScript綜合知識     

事件驅動是 WEB 前端的常態,所有互動都透過事件完成。常見的分類有 UI 事件、焦點事件、滑鼠事件、滾輪事件、文字事件、鍵盤事件與變動事件等。

問題來了:頁面上有一個輸入框,要對使用者輸入的字串做過濾或攔截處理,直覺做法是綁一個事件。但若同一個事件下掛了三段互不相干的邏輯,程式碼就會越長越難維護。本文示範如何用自訂事件把它拆開。

起點:直接在事件回呼裡寫完

window.onload = init;

function init () {
  var eText = document.getElementById("text");
  eText.addEventListener("keypress", function( ev ) {
    // 邏輯全部寫在這裡
    var code = ev.which || ev.keyCode || ev.charCode;
    console.log( code );
    if (code > 80) {
      console.log("code > 80");
    }
    if (ev.shiftKey === true) {
      console.log("shift key is pressed!");
    }
  });
}

第二步:把回呼內容抽成獨立函式

事件邏輯一多,可以整段抽出去:

var 我是事件 = function(ev) {
  var code = ev.which || ev.keyCode || ev.charCode;
  console.log( code );
  if (code > 80) { console.log("code > 80"); }
  if (ev.shiftKey === true) { console.log("shift key is pressed!"); }
};

function init () {
  document.getElementById("text")
    .addEventListener("keypress", function( ev ) { 我是事件(ev); });
}

清楚一些了。但在大型專案裡,我們想更彻底地解耦——把回呼中的三段邏輯各自獨立:

· 函式 A:console.log(code)

· 函式 B:if (code > 80) { ... }

· 函式 C:if (ev.shiftKey === true) { ... }

第三步:用自訂事件串起來

自訂事件的關鍵認知是:這些事件不會自動發生,必須由你的程式碼主動觸發。一個帶自訂事件的模組,需要提供一個公開方法來「拋出」事件,並把參數傳給所有訂閱的處理器。這正是觀察者模式/發布訂閱模式的基礎。

以下先實作一個精簡的 EventEmitter:

var EventEmitter = (function () {
  function EventEmitter() {
    this._events = {};
  }

  EventEmitter.prototype.emit = function (type) {
    var args = Array.prototype.slice.call(arguments, 1);
    if (type === 'error' && !this._events[type]) {
      throw args[0] instanceof Error ? args[0] : new Error("Uncaught error event.");
    }
    if (this._events[type]) {
      this._events[type].forEach(function (handler) {
        handler.apply(this, args);
      }, this);
      return true;
    }
    return false;
  };

  EventEmitter.prototype.addListener = function (type, listener) {
    if (typeof listener !== 'function') {
      throw new Error('addListener only takes instances of Function');
    }
    (this._events[type] = this._events[type] || []).push(listener);
    return this;
  };

  EventEmitter.prototype.removeListener = function (type, listener) {
    var listeners = this._events[type];
    if (!listeners) return this;
    var i = listeners.indexOf(listener);
    if (i >= 0) listeners.splice(i, 1);
    return this;
  };

  return EventEmitter;
})();

接著讓自訂的事件類別繼承它(ES5 的繼承寫法):

// d 為目標建構子,b 為父建構子
var __extends = function (d, b) {
  for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  function __() { this.constructor = d; }
  __.prototype = b.prototype;
  d.prototype = new __();
};

var TextEvent = (function (Emitter) {
  __extends(TextEvent, Emitter);
  function TextEvent() {
    Emitter.apply(this, arguments);
  }
  return TextEvent;
})(EventEmitter);

現在把三段邏輯各自掛成獨立的事件處理器:

window.onload = init;

function init () {
  var textEvent = new TextEvent();

  textEvent.addListener("keypress", function preventDefault(ev) {
    ev.preventDefault();
  });
  textEvent.addListener("keypress", function (ev) {
    console.log(ev.which || ev.keyCode || ev.charCode);
  });
  textEvent.addListener("keypress", function (ev) {
    var code = ev.which || ev.keyCode || ev.charCode;
    if (code > 80) { console.log("code > 80"); }
  });
  textEvent.addListener("keypress", function (ev) {
    if (ev.shiftKey === true) { console.log("shift key is pressed!"); }
  });

  // 原生事件只負責「轉發」
  document.getElementById("text").addEventListener("keypress", function (ev) {
    textEvent.emit("keypress", ev);
  });
}

這樣做換到了什麼

原生事件只負責把 DOM 事件轉發成自訂事件,真正的業務邏輯全部住在各自的處理器裡。好處有三:

· 可移除:removeListener 能精準摘掉某一個處理器,不必動到其他的。

· 可複用:同一個處理器函式可以掛到多個自訂事件上,甚至跨元件共用。

· 可擴充:新增一段邏輯只是多一行 addListener,不必碰原生事件的綁定處。

代價是程式碼量確實變多了——正如原始範例中那句吐槽。這是一筆需要權衡的交易:邏輯簡單時,直接寫在回呼裡最好;邏輯多、需要跨模組通知、或需要動態增刪處理器時,自訂事件才真正劃算。

現代的等價寫法

ES6 之後不必自己刻繼承了,原生就有 EventTarget 與 Node 的 EventEmitter:

class TextEvent extends EventTarget {
  constructor(){ super(); }
}

const bus = new TextEvent();
bus.addEventListener('keypress', (e) => console.log(e.detail));
bus.dispatchEvent(new CustomEvent('keypress', { detail: ev }));

若只是要在同一個 JS 環境內傳訊息,Node 的 require('events').EventEmitter 是現成且經過驗證的選擇,上面那份手刻版本可以直接換掉。另外提醒:原範例中 ev.which = ev.which || ... 是赋值而非取值,那是筆誤——多餘的赋值會改動事件物件,應寫成 var code = ev.which || ev.keyCode || ev.charCode;。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved