Skip to content
Closed
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
13 changes: 8 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ type EventHandlerMap = {
* @returns {Mitt}
*/
export default function mitt(all: EventHandlerMap) {
all = all || Object.create(null);
all = all || {};
let instance;

return {
return instance = {
/**
* Register an event handler for the given type.
*
Expand All @@ -26,7 +27,9 @@ export default function mitt(all: EventHandlerMap) {
* @memberOf mitt
*/
on(type: string, handler: EventHandler) {
(all[type] || (all[type] = [])).push(handler);
var arr = all[type] = all[type] || [];
arr.push(handler);
return instance.off.bind(instance, type, handler);
},

/**
Expand All @@ -38,8 +41,8 @@ export default function mitt(all: EventHandlerMap) {
* @memberOf mitt
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that's intentional.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the assignment isn't needed, just it produced a smaller output size because it is duplicated and thus cheap when gzipped. I'd be curious to see the size with & without this change.

*/
off(type: string, handler: EventHandler) {
let e = all[type] || (all[type] = []);
e.splice(e.indexOf(handler) >>> 0, 1);
var arr = all[type] || [];
arr.splice(arr.indexOf(handler) >>> 0, 1);
},

/**
Expand Down
18 changes: 18 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ describe('mitt#', () => {
expect(events).to.not.have.property('bar');
expect(events).to.have.property('baz:baT!').that.deep.equals([foo]);
});

it('should return unsubscribe function', () => {
let foo = () => {};
let off = inst.on('foo', foo);

expect(off).to.be.a('function');
});
});

describe('off()', () => {
Expand Down Expand Up @@ -91,6 +98,17 @@ describe('mitt#', () => {
expect(events).to.not.have.property('bar');
expect(events).to.have.property('baz:baT!').that.is.empty;
});

it('should remove handler if unsubscribe is called', () => {
let foo = () => {};
let off = inst.on('foo', foo);

expect(events).to.have.property('foo').that.deep.equals([foo]);

off();

expect(events).to.have.property('foo').that.is.empty;
});
});

describe('emit()', () => {
Expand Down