Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/GuideChimp.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ export default class GuideChimp {

this.cache = new Map();

this.listeners = {};
// Event names are caller-controlled, so keep them out of Object.prototype.
this.listeners = Object.create(null);

this.observers = {};

Expand Down Expand Up @@ -1534,7 +1535,7 @@ export default class GuideChimp {

const e = event.trim();

this.listeners[e] = this.listeners[e] || {};
this.listeners[e] = this.listeners[e] || Object.create(null);
this.listeners[e][priority] = this.listeners[e][priority] || [];
this.listeners[e][priority].push(listener);

Expand Down
43 changes: 43 additions & 0 deletions test/specs/emit.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import GuideChimp from '../../src/GuideChimp';

describe('GuideChimp event listeners', () => {
let guideChimp;

beforeEach(() => {
guideChimp = new GuideChimp([]);
});

it('registers listeners and emits arguments with the GuideChimp instance as this', async () => {
const listener = vi.fn(function listener(...args) {
expect(this).toBe(guideChimp);
return args.join(' ');
});

expect(guideChimp.on('customEvent', listener)).toBe(guideChimp);
await expect(guideChimp.emit('customEvent', 'hello', 'world')).resolves.toEqual(['hello world']);
expect(listener).toHaveBeenCalledOnce();
});

it('supports event names that exist on Object.prototype without modifying it', async () => {
const originalProperties = Object.getOwnPropertyNames(Object.prototype);
const listener = vi.fn();

guideChimp.on('__proto__', listener);
await guideChimp.emit('__proto__');

expect(listener).toHaveBeenCalledOnce();
expect(Object.getOwnPropertyNames(Object.prototype)).toEqual(originalProperties);
});

it('emits listeners from highest to lowest priority', async () => {
const calls = [];

guideChimp.on('customEvent', () => calls.push('low'), { priority: 'low' });
guideChimp.on('customEvent', () => calls.push('high'), { priority: 'high' });
guideChimp.on('customEvent', () => calls.push('critical'), { priority: 'critical' });

await guideChimp.emit('customEvent');

expect(calls).toEqual(['critical', 'high', 'low']);
});
});
Loading