@@ -271,10 +271,6 @@ export class DOMEvent implements Event {
271
271
this . target = target ;
272
272
this . defaultPrevented = false ;
273
273
274
- // Internal API to facilitate testing - to be removed once we've
275
- // completed the breaking changes to migrate fully to DOMEvents.
276
- DOMEvent . unstable_currentEvent = this ;
277
-
278
274
// `Observable.removeEventListener` would likely suffice, but grabbing
279
275
// the static method named `removeEventListener` on the target's class
280
276
// allows us to be robust to the possiblity of the case of the target
@@ -409,6 +405,25 @@ export class DOMEvent implements Event {
409
405
removeEventListener . call ( removeEventListenerContext , this . type , callback , thisArg , capture ) ;
410
406
}
411
407
408
+ // Internal API to facilitate testing - to be removed once we've
409
+ // completed the breaking changes to migrate fully to DOMEvents.
410
+ //
411
+ // We update DOMEvent.unstable_currentEvent just before each call to
412
+ // the callback. Doing it only in dispatchTo() would seem more
413
+ // efficient, but it wouldn't technically be correct as it's
414
+ // possible for a callback itself to dispatch another event. Because
415
+ // we handle events synchronously rather than using a queue, it
416
+ // would mean that DOMEvent.unstable_currentEvent would correctly
417
+ // point at the sub-event, but subsequently fail to update to point
418
+ // at the initial event.
419
+ //
420
+ // Note that this will fail to set itself back to null if the
421
+ // callback throws an error, but that's unlikely to break anything
422
+ // in practice as it's only intended be valid when accessed
423
+ // during the callback anyway. We reset it mainly just to stop
424
+ // retaining the event.
425
+ DOMEvent . unstable_currentEvent = this ;
426
+
412
427
// Consistent with the original implementation, we only apply
413
428
// context to the function if thisArg is truthy.
414
429
//
@@ -417,6 +432,8 @@ export class DOMEvent implements Event {
417
432
// nanoseconds per dispatchTo() call).
418
433
const returnValue = callback . call ( thisArg || undefined , data ) ;
419
434
435
+ DOMEvent . unstable_currentEvent = null ;
436
+
420
437
// This ensures that errors thrown inside asynchronous functions do
421
438
// not get swallowed.
422
439
//
0 commit comments