diff --git a/src/index.js b/src/index.js index 92b19f9..e72bcfa 100644 --- a/src/index.js +++ b/src/index.js @@ -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. * @@ -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); }, /** @@ -38,8 +41,8 @@ export default function mitt(all: EventHandlerMap) { * @memberOf mitt */ 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); }, /** diff --git a/test/index.js b/test/index.js index 61a3e67..96706b9 100644 --- a/test/index.js +++ b/test/index.js @@ -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()', () => { @@ -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()', () => {