DIV CSS 佈局教程網

JavaScript 自定義事件詳解:從原生 API 到跨瀏覽器封裝
編輯:JavaScript基礎知識     

自定義事件能讓開發變得更靈活。用得好,它是一件非常強力的工具——把彼此關聯但邏輯複雜的操作解耦開,讓觸發時機完全由自己掌控。相關的核心 API 有三個:Event、CustomEvent 和 dispatchEvent。

用 Event 構造函數直接造事件

var event = new Event('build');

// 監聽事件
elem.addEventListener('build', function (e) { ... }, false);

// 觸發事件
elem.dispatchEvent(event);

用 CustomEvent 攜帶數據

CustomEvent 能創建更高度自定義的事件,還可以附帶數據:

var myEvent = new CustomEvent(eventname, options);

其中 options 可以是:

{
  detail: { ... },
  bubbles: true,
  cancelable: false
}

detail 用來存放初始化信息,觸發時可以在回調裡取用;bubbles、cancelable 則分別定義該事件是否冒泡、是否可取消。

內置事件由瀏覽器在用戶操作時自動觸發,自定義事件則需要人工觸發,dispatchEvent 就是幹這個的:

element.dispatchEvent(customEvent);

組合起來使用:

// 添加合適的事件監聽器
obj.addEventListener("cat", function(e) { process(e.detail) });

// 創建並觸發事件
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchEvent(event);

用 jQuery 更省心

// 綁定自定義事件
$(element).on('myCustomEvent', function(){});

// 觸發事件
$(element).trigger('myCustomEvent');

jQuery 還支持在觸發時傳遞額外參數:

$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
});

$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});

老一點的寫法:createEvent + initEvent

<div id="testBox"></div>
// 創建事件
var evt = document.createEvent('Event');
// 定義事件類型
evt.initEvent('customEvent', true, true);
// 在元素上監聽事件
var obj = document.getElementById('testBox');
obj.addEventListener('customEvent', function(){
  console.log('customEvent 事件觸發了');
}, false);

在 console 中執行 obj.dispatchEvent(evt),可以看到輸出「customEvent 事件觸發了」。整個流程是:createEvent 創建空事件,initEvent 定義事件類型,然後在元素上監聽,最後用 dispatchEvent 觸發。

可見自定義事件的機制與普通事件一致——監聽事件、寫回調、觸發後執行回調。不同之處在於觸發時機完全由我們決定,這就實現了一種語義層面的解耦。

IE8 及以下怎麼辦

低版本 IE 並不支持 createEvent(),只有 IE 私有的 fireEvent(),而 fireEvent 又僅支持標準事件。於是流傳出一種取巧的模擬方案:

// type 為自定義事件,如 type = 'customEvent';callback 為開發者實際定義的回調函數
obj[type] = 0;
obj[type]++;
obj.attachEvent('onpropertychange', function(event){
  if( event.propertyName == type ){
    callback.call(obj);
  }
});

原理是在 DOM 上加一個自定義屬性,同時監聽元素的 propertychange 事件;當某個屬性值發生變化時觸發回調,再在回調中判斷變化的屬性是否就是我們約定的那個,若是則執行真正的回調。以此模擬出事件機制。

一個完整的事件機制封裝

下面的封裝同時支援標準事件與自定義事件的監聽、移除與模擬觸發,並支援鏈式調用。為了讓代碼邏輯更清晰,這裡約定自定義事件帶有 'custom' 前綴(例如 customTest、customAlert)。

/**
 * @description 包含事件監聽、移除和模擬事件觸發的事件機制,支持鏈式調用
 * */
(function( window, undefined ){
  var Ev = window.Ev = window.$ = function(element){
    return new Ev.fn.init(element);
  };

  // Ev 對象構建
  Ev.fn = Ev.prototype = {
    init: function(element){
      this.element = (element && element.nodeType == 1) ? element: document;
    },

    /**
     * 添加事件監聽
     * @param {String} type 監聽的事件類型
     * @param {Function} callback 回調函數
     */
    add: function(type, callback){
      var _that = this;
      if(_that.element.addEventListener){
        /** @supported For Modern Browers and IE9+ */
        _that.element.addEventListener(type, callback, false);
      } else if(_that.element.attachEvent){
        /** @supported For IE5+ */
        // 自定義事件處理
        if( type.indexOf('custom') != -1 ){
          if( isNaN( _that.element[type] ) ){
            _that.element[type] = 0;
          }
          var fnEv = function(event){
            event = event ? event : window.event
            if( event.propertyName == type ){
              callback.call(_that.element);
            }
          };
          _that.element.attachEvent('onpropertychange', fnEv);
          // 在元素上存儲綁定的 propertychange 回調,方便移除事件綁定
          if( !_that.element['callback' + callback] ){
            _that.element['callback' + callback] = fnEv;
          }
        // 標准事件處理
        } else {
          _that.element.attachEvent('on' + type, callback);
        }
      } else {
        /** @supported For Others */
        _that.element['on' + type] = callback;
      }
      return _that;
    },

    /**
     * 移除事件監聽
     * @param {String} type 監聽的事件類型
     * @param {Function} callback 回調函數
     */
    remove: function(type, callback){
      var _that = this;
      if(_that.element.removeEventListener){
        /** @supported For Modern Browers and IE9+ */
        _that.element.removeEventListener(type, callback, false);
      } else if(_that.element.detachEvent){
        /** @supported For IE5+ */
        // 自定義事件處理
        if( type.indexOf('custom') != -1 ){
          // 移除對相應的自定義屬性的監聽
          _that.element.detachEvent('onpropertychange', _that.element['callback' + callback]);
          // 刪除儲存在 DOM 上的自定義事件的回調
          _that.element['callback' + callback] = null;
        // 標准事件的處理
        } else {
          _that.element.detachEvent('on' + type, callback);
        }
      } else {
        /** @supported For Others */
        _that.element['on' + type] = null;
      }
      return _that;
    },

    /**
     * 模擬觸發事件
     * @param {String} type 模擬觸發事件的事件類型
     * @return {Object} 返回當前的 Kjs 對象
     */
    trigger: function(type){
      var _that = this;
      try {
        // 現代浏覽器
        if(_that.element.dispatchEvent){
          // 創建事件
          var evt = document.createEvent('Event');
          // 定義事件的類型
          evt.initEvent(type, true, true);
          // 觸發事件
          _that.element.dispatchEvent(evt);
        // IE
        } else if(_that.element.fireEvent){
          if( type.indexOf('custom') != -1 ){
            _that.element[type]++;
          } else {
            _that.element.fireEvent('on' + type);
          }
        }
      } catch(e){ };
      return _that;
    }
  }
  Ev.fn.init.prototype = Ev.fn;
})( window );

測試用例(自定義事件):

// 引入事件機制
// ...

// 捕捉 DOM
var testBox = document.getElementById('testbox');

// 回調函數 1
function triggerEvent(){
  console.log('觸發了一次自定義事件 customConsole');
}

// 回調函數 2
function triggerAgain(){
  console.log('再一次觸發了自定義事件 customConsole');
}

// 封裝
testBox = $(testBox);

// 同時綁定兩個回調函數,支持鏈式調用
testBox.add('customConsole', triggerEvent).add('customConsole', triggerAgain);

打開頁面後,在 console 中調用 testBox.trigger('customConsole') 自行觸發,可以看到輸出兩條提示;再執行 testBox.remove('customConsole', triggerAgain) 移除第二個監聽,此後再次觸發就只會輸出第一條——說明綁定、觸發、移除三項能力都正常工作。

什麼場景值得用自定義事件

當一個操作完成後需要通知多個互不相識的模塊時,自定義事件比層層回調更清爽;當觸發時機取決於業務狀態(而非用戶操作)時,它能把「什麼時候發生」與「發生後做什麼」徹底分開。這也是事件驅動架構在前端最基本的落點。

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