Skip to content

Commit

Permalink
fix: freeze object
Browse files Browse the repository at this point in the history
  • Loading branch information
sibiraj-s committed Jan 5, 2021
1 parent 3b7f3c4 commit 2102012
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
18 changes: 9 additions & 9 deletions capillaries.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
class Capillaries {
events = {};
#events = {};

constructor() {
Object.seal(this);
Object.freeze(this);
}

on = (type, listener, ctx = null) => {
if (typeof listener !== 'function') {
throw new TypeError('Event Listener must be a function');
}

const event = this.events[type] || [];
const event = this.#events[type] || [];
event.push([listener, ctx]);
this.events[type] = event;
this.#events[type] = event;
}

off = (type, listener) => {
if (typeof listener !== 'function') {
delete this.events[type];
delete this.#events[type];
return;
}

this.events[type] = (this.events[type] || []).filter((e) => e[0] !== listener);
this.#events[type] = (this.#events[type] || []).filter((e) => e[0] !== listener);
}

emit = (type, ...args) => {
const starEvents = type === '*' ? [] : this.events['*'] || [];
const eventList = (this.events[type] || []).concat(starEvents);
const starEvents = type === '*' ? [] : this.#events['*'] || [];
const eventList = (this.#events[type] || []).concat(starEvents);

eventList.forEach((event) => {
const [listenerFn, ctx] = event;
Expand All @@ -35,7 +35,7 @@ class Capillaries {
}

unbindAll = () => {
this.events = {};
this.#events = {};
}
}

Expand Down
5 changes: 4 additions & 1 deletion capillaries.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ it('should initiate correctly', () => {
expect(event.off).toBeInstanceOf(Function);
expect(event.emit).toBeInstanceOf(Function);
expect(event.unbindAll).toBeInstanceOf(Function);
expect(event.events).toBeInstanceOf(Object);
});

it('should bind to events and invoke events when emitted', () => {
Expand Down Expand Up @@ -163,6 +162,10 @@ it('should be immutable', () => {
const func = jest.fn();
const callbackFnQ = jest.fn();

expect(() => { event.on = func; }).toThrow(TypeError);
expect(() => { event.off = func; }).toThrow(TypeError);
expect(() => { event.emit = func; }).toThrow(TypeError);
expect(() => { event.unbindAll = func; }).toThrow(TypeError);
expect(() => { event.newFunc = func; }).toThrow(TypeError);

event.on('q', callbackFnQ);
Expand Down

0 comments on commit 2102012

Please sign in to comment.