我們可以自訂事件來實現更靈活的開發,事件用好了可以是一件很強大的工具,基於事件的開發有很多優勢(後面介紹)。
與自訂事件的函數有 Event、CustomEvent 和 dispatchEvent。
直接自訂事件,使用 Event 建構函式:
var event = new Event('build');// Listen for the event.elem.addEventListener('build', function (e) { ... }, false);// Dispatch the event.elem.dispatchEvent(event);
CustomEvent 可以建立一個更高度自訂事件,還可以附帶一些資料,具體用法如下:
var myEvent = new CustomEvent(eventname, options);
其中 options 可以是:
{ detail: { ... }, bubbles: true, cancelable: false}
其中 detail 可以存放一些初始化的資訊,可以在觸發的時候調用。其他屬性就是定義該事件是否具有冒泡等等功能。
內建的事件會由瀏覽器根據某些操作進行觸發,自訂的事件就需要人工觸發。dispatchEvent 函數就是用來觸發某個事件:
element.dispatchEvent(customEvent);
上面代碼錶示,在 element 上面觸發 customEvent 這個事件。結合起來用就是:
// add an appropriate event listenerobj.addEventListener("cat", function(e) { process(e.detail) });// create and dispatch the eventvar event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});obj.dispatchEvent(event);
使用自訂事件需要注意相容性問題,而使用 jQuery 就簡單多了:
// 綁定自訂事件$(element).on('myCustomEvent', function(){});// 觸發事件$(element).trigger('myCustomEvent');此外,你還可以在觸發自訂事件時傳遞更多參數資訊:$( "p" ).on( "myCustomEvent", function( event, myName ) { $( this ).text( myName + ", hi there!" );});$( "button" ).click(function () { $( "p" ).trigger( "myCustomEvent", [ "John" ] );});
JavaScript 自訂事件就是有別於如 click, submit 等標準事件的自行定製的事件,在敘述自訂事件有何好處之前,先來看一個自訂事件的例子:
<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);
具體效果可以查看 Demo,在 console 中輸入 obj.dispatchEvent(evt),可以看到 console 中輸出“customEvent 事件觸發了”,表示自訂事件成功觸發。
在這個過程中,createEvent 方法建立了一個空事件 evt,然後使用 initEvent 方法定義事件的類型為約定好的自訂事件,再對相應的元素進行監聽,接著,就是使用 dispatchEvent 觸發事件了。
沒錯,自訂事件的機制如普通事件一樣——監聽事件,寫回調操作,觸發事件後執行回調。但不同的是,自訂事件完全由我們控制觸發時機,這就意味著實現了一種 JavaScript 的解耦。我們可以把多個關聯但邏輯複雜的操作利用自訂事件的機制靈活地控制好。
當然,可能你已經猜到了,上面的代碼在低版本的 IE 中並不生效,事實上在 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 事件,當 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 );測試案例1(自訂事件測試)// 測試案例1(自訂事件測試)// 引入事件機制// ...// 捕捉 DOMvar testBox = document.getElementById('testbox');// 回呼函數1function triggerEvent(){ console.log('觸發了一次自訂事件 customConsole');}// 回呼函數2function triggerAgain(){ console.log('再一次觸發了自訂事件 customConsole');}// 封裝testBox = $(testBox);// 同時綁定兩個回呼函數,支援鏈式調用testBox.add('customConsole', triggerEvent).add('customConsole', triggerAgain);
完整的代碼在 Demo。
開啟 Demo 後,在 console 中調用 testBox.trigger('customConsole') 自行觸發自訂事件,可以看到 console 輸出兩個提示,再輸入 testBox.remove('customConsole', triggerAgain) 移除對後一個監聽,這時再使用 testBox.trigger('customConsole') 觸發自訂事件,可以看到 console 只輸出一個提示,即成功移除後一個監聽,至此事件機制所有功能正常工作。