我們可以自定義事件來實現更靈活的開發,事件用好了可以是一件很強大的工具,基於事件的開發有很多優勢(後面介紹)。
與自定義事件的函數有 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 listener
obj.addEventListener("cat", function(e) { process(e.detail) });
// create and dispatch the event
var 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(自定義事件測試)
// 引入事件機制
// ...
// 捕捉 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);
完整的代碼在 Demo。
打開 Demo 後,在 console 中調用 testBox.trigger('customConsole') 自行觸發自定義事件,可以看到 console 輸出兩個提示語,再輸入 testBox.remove('customConsole', triggerAgain) 移除對後一個監聽,這時再使用 testBox.trigger('customConsole') 觸發自定義事件,可以看到 console 只輸出一個提示語,即成功移除後一個監聽,至此事件機制所有功能正常工作。