Search code examples
javascriptcustom-events

event.initEvent vs event.initCustomEvent


I was working on a task related to Custom Events and was wondering, is there a difference between these methods apart from extra argument for event data

MDN - The old-fashioned way uses event.initEvent but the polyfill on MDN - Cutom Events uses event.initCustomEvent to initialize event.

I have referred Passing additional arguments in custom Event, but we can even use event.details to set event data.

JSFiddle - Event data with initEvent

So the question is, Is there any benefit of using specific one of them?


Solution

  • From the DOM spec:

    The initCustomEvent(type, bubbles, cancelable, detail) method must, when invoked, run these steps:

    1. If context object's dispatch flag is set, terminate these steps.
    2. Initialize the context object with type, bubbles, and cancelable.
    3. Set context object's detail attribute to detail.

    The initEvent(type, bubbles, cancelable) method, when invoked, must run these steps:

    1. If context object's dispatch flag is set, terminate these steps.
    2. Initialize the context object with type, bubbles, and cancelable.

    Note: As events have constructors initEvent() is superfluous. However, it has to be supported for legacy content.

    So, apart from the detail argument, they are the same.