Skip to content

Commit

Permalink
Retain order of existing event listeners when attempting to add redun…
Browse files Browse the repository at this point in the history
…dant listener
  • Loading branch information
ryanhamley committed May 18, 2018
1 parent a5da36c commit 549c6cd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
8 changes: 5 additions & 3 deletions src/util/evented.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ type Listener = (Object) => any;
type Listeners = { [string]: Array<Listener> };

function _addEventListener(type: string, listener: Listener, listenerList: Listeners) {
_removeEventListener(type, listener, listenerList);
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
18 changes: 10 additions & 8 deletions test/unit/util/evented.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,16 @@ test('Evented', (t) => {
});

t.test('on is idempotent', (t) => {
const evented = new Evented();
const listener = t.spy();
evented.on('a', listener);
evented.on('a', listener);
evented.on('a', listener);
evented.fire(new Event('a'));
t.ok(listener.calledOnce);
t.end();
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) => {
Expand Down

0 comments on commit 549c6cd

Please sign in to comment.