此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
EventTarget
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
* Some parts of this feature may have varying levels of support.
EventTarget 介面定義了其實作的物件具有接收事件的能力,也可能擁有處理事件的監聽器。
除了最為常見的Element、Document 與Window 繼承或實作了EventTarget 介面之外,其它的物件還有XMLHttpRequest、AudioNode、AudioContext⋯ 等等。
許多EventTarget(包括 Element、Document 和 Window)除了透過addEventListener() 方法外,還可藉由DOM 物件的屬性(property)或HTML 元素屬性(attribute)來設定事件處理器。
In this article
方法
EventTarget.addEventListener()於
EventTarget物件上註冊指定事件的監聽器。EventTarget.removeEventListener()移除
EventTarget物件上的指定事件監聽器。EventTarget.dispatchEvent()對此
EventTarget物件派送(dispatch)一個事件物件,也就是於此EventTarget物件上觸發一個指定的事件物件實體。
Mozilla chrome code 的額外方法
Mozilla extensions for use by JS-implemented event targets to implement on properties. See alsoWebIDL bindings.
- voidsetEventHandler(DOMString type, EventHandler handler)Non-standard
- EventHandlergetEventHandler(DOMString type)Non-standard
範例
>Simple implementation of EventTarget
var EventTarget = function () { this.listeners = {};};EventTarget.prototype.listeners = null;EventTarget.prototype.addEventListener = function (type, callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(callback);};EventTarget.prototype.removeEventListener = function (type, callback) { if (!(type in this.listeners)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback) { stack.splice(i, 1); return; } }};EventTarget.prototype.dispatchEvent = function (event) { if (!(event.type in this.listeners)) { return true; } var stack = this.listeners[event.type]; event.target = this; for (var i = 0, l = stack.length; i < l; i++) { stack[i].call(this, event); } return !event.defaultPrevented;};規範
| Specification |
|---|
| DOM> # interface-eventtarget> |
瀏覽器相容性
參見
- Event reference - the events available in the platform.
- Event developer guide
Eventinterface