CustomEvent()

CustomEvent() constructor 可用來建立 CustomEvent.

語法

 event = new CustomEvent(typeArg, customEventInit);

參數

typeArg
一個 DOMString 用來表示事件名稱。
customEventInit選擇性
Is a CustomEventInit dictionary, having the following fields:
  • "detail", optional and defaulting to null, of type any, that is a event-dependant value associated with the event.

The CustomEventInit dictionary also accepts fields from the EventInit dictionary.

範例

// 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);

規格

Specification Status Comment
DOM
The definition of 'CustomEvent()' in that specification.
Living Standard Initial definition.

瀏覽器支援度

BCD tables only load in the browser

添加額外參數

在 Internet Explorer 9 或更高的版本,你可以用以下的方法給 CustomEvent() constructor 添加額外參數

(function () {
  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   }

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();

延伸閱讀