CustomEvent()

The CustomEvent() constructor creates a new CustomEvent.

构造方法 CustomerEvent() 创建一个新的 CustomEvent 对象。

Syntax 语法

 event = new CustomEvent(typeArg, customEventInit);

Values 参数

typeArg
Is a DOMString representing the name of the event.
一个表示 event 名字的字符串
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.   可选的默认值是 null 的任意类型数据,是一个与 event 相关的值
  • bubbles 一个布尔值,表示该事件能否冒泡。 来自 EventInit
  • cancelable 一个布尔值,表示该事件是否可以取消。 来自 EventInit

The CustomEventInit dictionary also accepts fields from the EventInit dictionary.

CustomerEventInit 字典参数同样接受来自于 Event 类构造函数的 eventInit 字典参数,如下

bubbles   一个布尔值,表示该事件能否冒泡

cancelable  一个布尔值,表示该事件是否可以取消

Example

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

Specifications

Specification Status Comment
DOM
CustomEvent()
Living Standard Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
BasicSupport 15 11 (11) 未实现 11.60 Nightly build (535.2)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support ? 11.0 (11) ? ? ?

Polyfill

You can polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher with the following code:

(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;
})();

See also

文档标签和贡献者