Skip to content

Commit

Permalink
Ensure that destroy is always returned
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Mar 11, 2019
1 parent 23eff24 commit 3f54e6d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
40 changes: 21 additions & 19 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,7 @@ function _delegate(
}
};

const elementMap = elements.get(element) || new WeakMap();
const setups = elementMap.get(callback) || new Set();
for (const setup of setups) {
if (setup.selector === selector && setup.type === type && setup.useCapture === useCapture) {
return;
}
}

// Remember event in tree
elements.set(element,
elementMap.set(callback,
setups.add({selector, type, useCapture})
)
);

// Add event on delegate
element.addEventListener(type, listenerFn, useCapture);

return {
const delegateSubscription = {
destroy() {
element.removeEventListener(type, listenerFn, useCapture);
if (!elements.has(element)) {
Expand Down Expand Up @@ -63,6 +45,26 @@ function _delegate(
}
}
};

const elementMap = elements.get(element) || new WeakMap();
const setups = elementMap.get(callback) || new Set();
for (const setup of setups) {
if (setup.selector === selector && setup.type === type && setup.useCapture === useCapture) {
return delegateSubscription;
}
}

// Remember event in tree
elements.set(element,
elementMap.set(callback,
setups.add({selector, type, useCapture})
)
);

// Add event on delegate
element.addEventListener(type, listenerFn, useCapture);

return delegateSubscription;
}

/**
Expand Down
6 changes: 4 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ test.cb('should add an event listener only once', t => {
const handler = () => {
t.end();
};
delegate(container, 'a', 'click', handler);
delegate(container, 'a', 'click', handler);
const first = delegate(container, 'a', 'click', handler);
const second = delegate(container, 'a', 'click', handler);
anchor.click();
t.is(first && typeof first.destroy, 'function');
t.is(second && typeof second.destroy, 'function');
});

test('should remove an event listener', t => {
Expand Down

0 comments on commit 3f54e6d

Please sign in to comment.