Is dispatchEvent a sync or an async function
Asked Answered
R

2

30

I am trying to write an event handler for a custom event in WinJS. I am not too sure how this works in IE - I am creating a custom event and dispatching it -

var eventObject = document.createEvent("CustomEvent");
eventObject.initCustomEvent("dropbomb", true, true, null);
this._element.dispatchEvent(eventObject);

My handler is -

this._element.addEventListener("logtelemetry", function () {
                console.log("boom");
});

Can I be certain that the handler will be called in sync and not at a later time? If so then what is the proof.

Rawley answered 7/3, 2013 at 17:27 Comment(4)
@Mathletics, why? if you manually dispatch event, why won't it fire immediately?Snowy
@Snowy I suppose I don't know. Upon reading the documentation, the behavior really isn't clear.Taeniasis
@Mathletics, the point of my answer... :)Snowy
@Snowy yes, and my comment was previous to your answer. And by making a mistake and being corrected, I have learned, and am now wiser. Huzzah! :)Taeniasis
S
44

It’s guaranteed to be synchronous because:

The return value of dispatchEvent indicates whether any of the listeners which handled the event called preventDefault.

Since the return value indicates whether any of the listeners that handled the event called preventDefault, the method must block (not return) until all of the listeners are done executing, which is the definition of a synchronous call.

The above quotation is an excerpt from the dispatchEvent specification in DOM Level 2 Events, which achieved “Recommendation” status (a standard) back in November 2000. Internet Explorer has complied with this standard since at least IE 9.

To verify for yourself, add a console.log statement immediately after your .dispatchEvent call and notice that "boom" (from your event handler) is always logged first.

Stutsman answered 7/4, 2014 at 23:20 Comment(2)
+1 thank you for kindly letting me know I was wrong!Snowy
This is exactly how i found out it's synchronous, put console.log right after the call and expect the result right away, amazing!!Pyorrhea
K
2

The handler will be called immediately, using the default implementation of the WinJS.Utilities.eventMixin. Theres no deferral.

Your individual handlers can chose to do deferred work by using setTimeout/setImmediate/setInterval/requestAnimationFrame, or some other custom rolled implementation.

Note that if you are talking about DOM events, asking them to bubble up the DOM element tree - that I'm not 100% clear on (maybe someone can add that specific here)

Keratoplasty answered 7/3, 2013 at 17:27 Comment(1)
Looking forward to see the setImmediate specification as a standard!Emsmus

© 2022 - 2024 — McMap. All rights reserved.