1+ import { arrayFlatten , getGlobalContext , Logger , useDispose } from 'zeed'
12import type { DisposerFunction } from 'zeed'
2- import { Logger , arrayFlatten , getGlobalContext , useDispose } from 'zeed'
33import { ZContext } from './types'
44
55const log = Logger ( 'zerva:context' )
@@ -45,7 +45,9 @@ export async function emit<U extends keyof ZContextEvents>(
4545 ...args : Parameters < ZContextEvents [ U ] >
4646) : Promise < boolean > {
4747 log ( 'emit' , event , JSON . stringify ( args . map ( o => typeof o ) ) )
48- return await getContext ( ) . emit ( event , ...args )
48+ const ctx = getContext ( )
49+ ctx . eventNamesEmitted [ event ] = true
50+ return await ctx . emit ( event , ...args )
4951}
5052
5153/** Listener that binds to the current global context */
@@ -62,12 +64,21 @@ export function on<U extends keyof ZContextEvents>(
6264 first : Partial < ZContextEvents > | U ,
6365 listener ?: ZContextEvents [ U ] ,
6466) : DisposerFunction {
65- if ( typeof first === 'string' && listener != null )
66- return getContext ( ) . on ( first , listener )
67+ const ctx = getContext ( )
6768
69+ // Single
70+ if ( typeof first === 'string' && listener != null ) {
71+ if ( ctx . eventNamesEmitted [ first ] )
72+ log . warn ( `Event '${ first } ' has already been emitted before listener was added` )
73+ return ctx . on ( first , listener )
74+ }
75+
76+ // Multiple
6877 const dispose = useDispose ( )
6978 Object . entries ( first ) . forEach ( ( [ k , v ] ) => {
70- dispose . add ( getContext ( ) . on ( k as any , v ) )
79+ if ( ctx . eventNamesEmitted [ k ] )
80+ log . warn ( `Event '${ first } ' has already been emitted before listener was added` )
81+ dispose . add ( ctx . on ( k as any , v ) )
7182 } )
7283 return dispose
7384}
@@ -81,12 +92,21 @@ export function once<U extends keyof ZContextEvents>(
8192 first : Partial < ZContextEvents > | U ,
8293 listener ?: ZContextEvents [ U ] ,
8394) : DisposerFunction {
84- if ( typeof first === 'string' && listener != null )
85- return getContext ( ) . once ( first , listener )
95+ const ctx = getContext ( )
96+
97+ // Single
98+ if ( typeof first === 'string' && listener != null ) {
99+ if ( ctx . eventNamesEmitted [ first ] )
100+ log . warn ( `Event '${ first } ' has already been emitted before listener was added` )
101+ return ctx . once ( first , listener )
102+ }
86103
104+ // Multiple
87105 const dispose = useDispose ( )
88106 Object . entries ( first ) . forEach ( ( [ k , v ] ) => {
89- dispose . add ( getContext ( ) . once ( k as any , v ) )
107+ if ( ctx . eventNamesEmitted [ k ] )
108+ log . warn ( `Event '${ first } ' has already been emitted before listener was added` )
109+ dispose . add ( ctx . once ( k as any , v ) )
90110 } )
91111 return dispose
92112}
0 commit comments