File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -14,9 +14,10 @@ type EventHandlerMap = {
1414 * @returns {Mitt }
1515 */
1616export default function mitt ( all : EventHandlerMap ) {
17- all = all || Object . create ( null ) ;
17+ all = all || { } ;
18+ let instance ;
1819
19- return {
20+ return instance = {
2021 /**
2122 * Register an event handler for the given type.
2223 *
@@ -26,7 +27,9 @@ export default function mitt(all: EventHandlerMap) {
2627 * @memberOf mitt
2728 */
2829 on ( type : string , handler : EventHandler ) {
29- ( all [ type ] || ( all [ type ] = [ ] ) ) . push ( handler ) ;
30+ var arr = all [ type ] = all [ type ] || [ ] ;
31+ arr . push ( handler ) ;
32+ return instance . off . bind ( instance , type , handler ) ;
3033 } ,
3134
3235 /**
@@ -38,8 +41,8 @@ export default function mitt(all: EventHandlerMap) {
3841 * @memberOf mitt
3942 */
4043 off ( type : string , handler : EventHandler ) {
41- let e = all [ type ] || ( all [ type ] = [ ] ) ;
42- e . splice ( e . indexOf ( handler ) >>> 0 , 1 ) ;
44+ var arr = all [ type ] || [ ] ;
45+ arr . splice ( arr . indexOf ( handler ) >>> 0 , 1 ) ;
4346 } ,
4447
4548 /**
Original file line number Diff line number Diff line change @@ -58,6 +58,13 @@ describe('mitt#', () => {
5858 expect ( events ) . to . not . have . property ( 'bar' ) ;
5959 expect ( events ) . to . have . property ( 'baz:baT!' ) . that . deep . equals ( [ foo ] ) ;
6060 } ) ;
61+
62+ it ( 'should return unsubscribe function' , ( ) => {
63+ let foo = ( ) => { } ;
64+ let off = inst . on ( 'foo' , foo ) ;
65+
66+ expect ( off ) . to . be . a ( 'function' ) ;
67+ } ) ;
6168 } ) ;
6269
6370 describe ( 'off()' , ( ) => {
@@ -91,6 +98,17 @@ describe('mitt#', () => {
9198 expect ( events ) . to . not . have . property ( 'bar' ) ;
9299 expect ( events ) . to . have . property ( 'baz:baT!' ) . that . is . empty ;
93100 } ) ;
101+
102+ it ( 'should remove handler if unsubscribe is called' , ( ) => {
103+ let foo = ( ) => { } ;
104+ let off = inst . on ( 'foo' , foo ) ;
105+
106+ expect ( events ) . to . have . property ( 'foo' ) . that . deep . equals ( [ foo ] ) ;
107+
108+ off ( ) ;
109+
110+ expect ( events ) . to . have . property ( 'foo' ) . that . is . empty ;
111+ } ) ;
94112 } ) ;
95113
96114 describe ( 'emit()' , ( ) => {
You can’t perform that action at this time.
0 commit comments