Skip to content

Commit

Permalink
fix(user-interaction): event listeners have wrong this when listening…
Browse files Browse the repository at this point in the history
… for bubbled events (#643)

Co-authored-by: Daniel Dyla <dyladan@users.noreply.github.com>
  • Loading branch information
t2t2 and dyladan committed Aug 31, 2021
1 parent 8584432 commit f0fa800
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
Expand Up @@ -267,7 +267,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase<unknown>
useCapture: any
) {
const once = useCapture && useCapture.once;
const patchedListener = (...args: any[]) => {
const patchedListener = function (this: HTMLElement, ...args: any[]) {
let parentSpan: api.Span | undefined;
const event: Event | undefined = args[0];
const target = event?.target;
Expand All @@ -285,14 +285,14 @@ export class UserInteractionInstrumentation extends InstrumentationBase<unknown>
return api.context.with(
api.trace.setSpan(api.context.active(), span),
() => {
const result = plugin._invokeListener(listener, target, args);
const result = plugin._invokeListener(listener, this, args);
// no zone so end span immediately
span.end();
return result;
}
);
} else {
return plugin._invokeListener(listener, target, args);
return plugin._invokeListener(listener, this, args);
}
};
if (plugin.addPatchedListener(this, type, listener, patchedListener)) {
Expand Down
Expand Up @@ -486,7 +486,11 @@ describe('UserInteractionInstrumentation', () => {
btn2.setAttribute('id', 'btn2');
root.appendChild(btn2);

root.addEventListener('click', event => {
const listenerThis: EventTarget[] = [];
root.addEventListener('click', function (event) {
// Assert here with failure would also affect other tests due to setTimeout bellow
listenerThis.push(this);

switch (event.target) {
case btn1:
getData(FILE_URL, () => {
Expand All @@ -506,6 +510,17 @@ describe('UserInteractionInstrumentation', () => {

sandbox.clock.tick(1000);
originalSetTimeout(() => {
assert.strictEqual(
listenerThis[0],
root,
'this inside event listener matches listened target (0)'
);
assert.strictEqual(
listenerThis[1],
root,
'this inside event listener matches listened target (1)'
);

assert.equal(exportSpy.args.length, 4, 'should export 4 spans');

const span1: tracing.ReadableSpan = exportSpy.args[0][0][0];
Expand Down

0 comments on commit f0fa800

Please sign in to comment.