Skip to content
This repository has been archived by the owner on Mar 13, 2018. It is now read-only.

Commit

Permalink
Merge pull request #457 from arv/event-reentrancy
Browse files Browse the repository at this point in the history
Fix issue with event reentrancy
  • Loading branch information
dfreedm committed Jun 11, 2014
2 parents 26f93ae + 8b59c27 commit 7004965
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/wrappers/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,10 @@
targetTable.set(event, target);
currentTargetTable.set(event, currentTarget);

// Keep track of the invoke depth so that we only clean up the removed
// listeners if we are in the outermost invoke.
listeners.depth++;

for (var i = 0, len = listeners.length; i < len; i++) {
var listener = listeners[i];
if (listener.removed) {
Expand Down Expand Up @@ -410,7 +414,9 @@
}
}

if (anyRemoved) {
listeners.depth--;

if (anyRemoved && listeners.depth === 0) {
var copy = listeners.slice();
listeners.length = 0;
for (var i = 0; i < copy.length; i++) {
Expand Down Expand Up @@ -707,6 +713,7 @@
var listeners = listenersTable.get(this);
if (!listeners) {
listeners = [];
listeners.depth = 0;
listenersTable.set(this, listeners);
} else {
// Might have a duplicate.
Expand Down
28 changes: 28 additions & 0 deletions test/js/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -1448,4 +1448,32 @@ test('retarget order (multiple shadow roots)', function() {
assert.equal(gCount, 2);
assert.equal(hCount, 1);
});

test('Event reentrancy', function() {
div = document.createElement('div');
document.body.appendChild(div);
var s = '';
var depth = 0;

function f() {
s += 'f' + depth;
if (depth === 0) {
depth++;
div.dispatchEvent(new Event('x'));
} else if (depth === 1) {
div.removeEventListener('x', g);
}
}

function g() {
s += 'g' + depth;
}

div.addEventListener('x', f);
div.addEventListener('x', g);

div.dispatchEvent(new Event('x'));

assert.equal(s, 'f0f1');
});
});

0 comments on commit 7004965

Please sign in to comment.