Skip to content

Commit

Permalink
Make evented#addEventListener idempotent
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanhamley committed May 18, 2018
1 parent 6b82353 commit bac1f67
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/util/evented.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ type Listener = (Object) => any;
type Listeners = { [string]: Array<Listener> };

function _addEventListener(type: string, listener: Listener, listenerList: Listeners) {
listenerList[type] = listenerList[type] || [];
listenerList[type].push(listener);
const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;
if (!listenerExists) {
listenerList[type] = listenerList[type] || [];
listenerList[type].push(listener);
}
}

function _removeEventListener(type: string, listener: Listener, listenerList: Listeners) {
Expand Down
13 changes: 13 additions & 0 deletions test/unit/util/evented.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@ test('Evented', (t) => {
t.end();
});

t.test('on is idempotent', (t) => {
const evented = new Evented();
const listenerA = t.spy();
const listenerB = t.spy();
evented.on('a', listenerA);
evented.on('a', listenerB);
evented.on('a', listenerA);
evented.fire(new Event('a'));
t.ok(listenerA.calledOnce);
t.ok(listenerA.calledBefore(listenerB));
t.end();
});

t.test('evented parents', (t) => {

t.test('adds parents with "setEventedParent"', (t) => {
Expand Down

0 comments on commit bac1f67

Please sign in to comment.