fastevent 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.changeset/README.md +8 -0
  2. package/.changeset/config.json +11 -0
  3. package/.github/workflows/publish.yaml +50 -0
  4. package/.vscode/launch.json +20 -0
  5. package/CHANGELOG.md +7 -0
  6. package/LICENSE +21 -0
  7. package/bench.png +0 -0
  8. package/dist/index.d.mts +201 -0
  9. package/dist/index.d.ts +201 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/index.mjs +2 -0
  13. package/dist/index.mjs.map +1 -0
  14. package/package.json +34 -12
  15. package/readme.md +282 -0
  16. package/src/__benchmarks__/index.ts +3 -0
  17. package/src/__benchmarks__/multi-level.ts +40 -0
  18. package/src/__benchmarks__/sample.ts +40 -0
  19. package/src/__benchmarks__/wildcard.ts +41 -0
  20. package/src/__tests__/emit.test.ts +81 -0
  21. package/src/__tests__/emitAsync.test.ts +65 -0
  22. package/src/__tests__/isPathMatched.test.ts +205 -0
  23. package/src/__tests__/many.test.ts +23 -0
  24. package/src/__tests__/meta.test.ts +29 -0
  25. package/src/__tests__/off.test.ts +214 -0
  26. package/src/__tests__/onany.test.ts +173 -0
  27. package/src/__tests__/once.test.ts +71 -0
  28. package/src/__tests__/retain.test.ts +66 -0
  29. package/src/__tests__/scope.test.ts +111 -0
  30. package/src/__tests__/waitFor.test.ts +109 -0
  31. package/src/__tests__/wildcard.test.ts +186 -0
  32. package/src/event.ts +455 -5
  33. package/src/index.ts +3 -1
  34. package/src/scope.ts +88 -0
  35. package/src/types.ts +50 -0
  36. package/src/typestest.ts +102 -0
  37. package/src/utils/isPathMatched.ts +40 -0
  38. package/src/utils/removeItem.ts +16 -0
  39. package/tsconfig.json +112 -0
  40. package/tsup.config.ts +19 -0
@@ -0,0 +1,186 @@
1
+ import { describe, test, expect } from "vitest"
2
+ import { FastEvent } from "../event"
3
+ import { FastEventSubscriber } from "../types"
4
+
5
+
6
+ describe("基于通配符的发布与订阅",async ()=>{
7
+
8
+ test("使用通配符发布订阅层级事件",()=>{
9
+ const emitter = new FastEvent()
10
+ const events:string[]=[]
11
+ const subscribers:FastEventSubscriber[]=[]
12
+ subscribers.push(emitter.on("*/*/*",(payload,{type})=>{
13
+ expect(type).toBe("a/b/c")
14
+ expect(payload).toBe(1)
15
+ events.push(type)
16
+ }))
17
+ subscribers.push(emitter.on("a/*/*",(payload,{type})=>{
18
+ expect(type).toBe("a/b/c")
19
+ expect(payload).toBe(1)
20
+ events.push(type)
21
+ }))
22
+ subscribers.push(emitter.on("a/b/*",(payload,{type})=>{
23
+ expect(type).toBe("a/b/c")
24
+ expect(payload).toBe(1)
25
+ events.push(type)
26
+ }))
27
+ emitter.emit("a/b/c",1)
28
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c"])
29
+ emitter.emit("a/b/c",1)
30
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c","a/b/c","a/b/c","a/b/c"])
31
+ subscribers.forEach(subscriber=>subscriber.off())
32
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c","a/b/c","a/b/c","a/b/c"])
33
+ })
34
+
35
+ test("使用通配符发布订阅层级事件11",()=>{
36
+ const emitter = new FastEvent()
37
+ const events:string[]=[]
38
+ const subscribers:FastEventSubscriber[]=[]
39
+ subscribers.push(emitter.on("*/*/*",(payload,{type})=>{
40
+ expect(type).toBe("a/b/c")
41
+ expect(payload).toBe(1)
42
+ events.push(type)
43
+ }))
44
+ emitter.emit("a/b/c",1)
45
+ expect(events).toEqual(["a/b/c"])
46
+ })
47
+
48
+
49
+ test("使用通配符发布订阅层级事件12",()=>{
50
+ const emitter = new FastEvent()
51
+ const events:string[]=[]
52
+ const subscribers:FastEventSubscriber[]=[]
53
+ subscribers.push(emitter.on("a/*/*",(payload,{type})=>{
54
+ expect(type).toBe("a/b/c")
55
+ expect(payload).toBe(1)
56
+ events.push(type)
57
+ }))
58
+ emitter.emit("a/b/c",1)
59
+ expect(events).toEqual(["a/b/c"])
60
+ })
61
+ test("使用通配符发布订阅层级事件13",()=>{
62
+ const emitter = new FastEvent()
63
+ const events:string[]=[]
64
+ const subscribers:FastEventSubscriber[]=[]
65
+ subscribers.push(emitter.on("a/b/*",(payload,{type})=>{
66
+ expect(type).toBe("a/b/c")
67
+ expect(payload).toBe(1)
68
+ events.push(type)
69
+ }))
70
+ emitter.emit("a/b/c",1)
71
+ expect(events).toEqual(["a/b/c"])
72
+ })
73
+
74
+ test("使用通配符发布订阅层级事件14",()=>{
75
+ const emitter = new FastEvent()
76
+ const events:string[]=[]
77
+ const subscribers:FastEventSubscriber[]=[]
78
+ subscribers.push(emitter.on("*/*/*",(payload,{type})=>{
79
+ expect(type).toBe("a/b/c")
80
+ expect(payload).toBe(1)
81
+ events.push(type)
82
+ }))
83
+ subscribers.push(emitter.on("*/*/c",(payload,{type})=>{
84
+ expect(type).toBe("a/b/c")
85
+ expect(payload).toBe(1)
86
+ events.push(type)
87
+ }))
88
+ subscribers.push(emitter.on("*/b/c",(payload,{type})=>{
89
+ expect(type).toBe("a/b/c")
90
+ expect(payload).toBe(1)
91
+ events.push(type)
92
+ }))
93
+ emitter.emit("a/b/c",1)
94
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c"])
95
+ emitter.emit("a/b/c",1)
96
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c","a/b/c","a/b/c","a/b/c"])
97
+ subscribers.forEach(subscriber=>subscriber.off())
98
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c","a/b/c","a/b/c","a/b/c"])
99
+ })
100
+ test("使用通配符发布订阅层级事件15",()=>{
101
+ const emitter = new FastEvent()
102
+ const events:string[]=[]
103
+ const subscribers:FastEventSubscriber[]=[]
104
+ subscribers.push(emitter.on("*/b/c",(payload,{type})=>{
105
+ expect(type).toBe("a/b/c")
106
+ expect(payload).toBe(1)
107
+ events.push(type)
108
+ }))
109
+ emitter.emit("a/b/c",1)
110
+ expect(events).toEqual(["a/b/c"])
111
+ })
112
+ test("使用通配符发布订阅层级事件16",()=>{
113
+ const emitter = new FastEvent()
114
+ const events:string[]=[]
115
+ const subscribers:FastEventSubscriber[]=[]
116
+ subscribers.push(emitter.on("*/b/*/d/*/f",(payload,{type})=>{
117
+ events.push(type)
118
+ }))
119
+ emitter.emit("1/b/1/d/1/f",1)
120
+ emitter.emit("2/b/2/d/2/f",1)
121
+ emitter.emit("3/b/3/d/3/f",1)
122
+ emitter.emit("4/b/4/d/4/f",1)
123
+ emitter.emit("5/b/5/d/5/f",1)
124
+ expect(events).toEqual(["1/b/1/d/1/f","2/b/2/d/2/f","3/b/3/d/3/f","4/b/4/d/4/f","5/b/5/d/5/f"])
125
+ })
126
+ test("使用通配符发布订阅层级事件17",()=>{
127
+ return new Promise<void>((resolve) => {
128
+ const emitter = new FastEvent()
129
+ emitter.on('a/b/c/*', () => {
130
+ resolve()
131
+ })
132
+ emitter.emit('a/b/c/x', 1)
133
+ emitter.emit('a/b/c/x', 1)
134
+ })
135
+ })
136
+ test("使用多级路径匹配",()=>{
137
+ const emitter = new FastEvent()
138
+ const payloads:number[]=[]
139
+ const events:string[]=[]
140
+ emitter.on("a/**",(payload,{type})=>{
141
+ events.push(type)
142
+ payloads.push(payload)
143
+ })
144
+ emitter.emit("a/b/c/d/e/f",1)
145
+ expect(events).toEqual(["a/b/c/d/e/f"])
146
+ expect(payloads).toEqual([1])
147
+ })
148
+ test("使用多级路径匹配2",()=>{
149
+ const emitter = new FastEvent()
150
+ const payloads:number[]=[]
151
+ const events:string[]=[]
152
+ emitter.on("a/**",(payload,{type})=>{
153
+ events.push(type)
154
+ payloads.push(payload)
155
+ })
156
+
157
+ emitter.emit("a/b",1)
158
+ emitter.emit("a/b/c",2)
159
+ emitter.emit("a/b/c/d",3)
160
+ emitter.emit("a/b/c/d/e",4)
161
+ emitter.emit("a/b/c/d/e/f",5)
162
+ expect(events).toEqual(["a/b","a/b/c","a/b/c/d","a/b/c/d/e","a/b/c/d/e/f"])
163
+ expect(payloads).toEqual([1,2,3,4,5])
164
+ })
165
+ test("使用多级路径匹配3",()=>{
166
+ const emitter = new FastEvent()
167
+ const payloads:number[]=[]
168
+ const events:string[]=[]
169
+ emitter.on("a/**",(payload,{type})=>{
170
+ events.push(type)
171
+ payloads.push(payload)
172
+ })
173
+ emitter.on("a/b/*",(payload,{type})=>{
174
+ events.push(type)
175
+ payloads.push(payload)
176
+ })
177
+ emitter.emit("a/b/c",1)
178
+ emitter.emit("a/b/c/d",2)
179
+ emitter.emit("a/b/c/d/e",3)
180
+ emitter.emit("a/b/c/d/e/f",4)
181
+ expect(events).toEqual(["a/b/c","a/b/c","a/b/c/d","a/b/c/d/e","a/b/c/d/e/f"])
182
+ expect(payloads).toEqual([1,1,2,3,4])
183
+ })
184
+ })
185
+
186
+
package/src/event.ts CHANGED
@@ -1,5 +1,455 @@
1
-
2
-
3
- export class FastEvent{
4
-
5
- }
1
+ import { FastEventScope } from './scope';
2
+ import {
3
+ FastEventListener,
4
+ FastEventOptions,
5
+ FastEvents,
6
+ FastListeners,
7
+ FastListenerNode,
8
+ FastEventSubscriber,
9
+ ScopeEvents,
10
+ FastEventMeta
11
+ } from './types';
12
+ import { isPathMatched } from './utils/isPathMatched';
13
+ import { removeItem } from './utils/removeItem';
14
+
15
+ export class FastEvent<
16
+ Events extends FastEvents = FastEvents,
17
+ Types extends keyof Events = keyof Events,
18
+ Meta = unknown
19
+ >{
20
+ public listeners : FastListeners = { __listeners: [] } as unknown as FastListeners
21
+ private _options : FastEventOptions
22
+ private _delimiter : string = '/'
23
+ private _context : any
24
+ private _retainedEvents : Map<string,any> = new Map<string,any>()
25
+ constructor(options?:FastEventOptions<Meta>) {
26
+ this._options = Object.assign({
27
+ delimiter : '/',
28
+ context : null,
29
+ ignoreErrors : true
30
+ }, options)
31
+ this._delimiter = this._options.delimiter!
32
+ this._context = this._options.context || this
33
+ }
34
+ get options(){ return this._options }
35
+ private _addListener(parts:string[],listener:FastEventListener<any,any>,count?:number):FastListenerNode | undefined{
36
+ return this._forEachNodes(parts,(node)=>{
37
+ node.__listeners.push(count && count >0 ? [listener,count]: listener)
38
+ if(typeof(this._options.onAddListener)==='function'){
39
+ this._options.onAddListener(parts,listener)
40
+ }
41
+ })
42
+ }
43
+ /**
44
+ *
45
+ * 根据parts路径遍历侦听器树,并在最后的节点上执行回调函数
46
+ *
47
+ * @param parts
48
+ * @param callback
49
+ * @returns
50
+ */
51
+ private _forEachNodes(parts:string[],callback:(node:FastListenerNode,parent:FastListenerNode)=>void):FastListenerNode | undefined{
52
+ if(parts.length === 0) return
53
+ let current = this.listeners
54
+ for(let i=0;i<parts.length;i++){
55
+ const part = parts[i]
56
+ if(!(part in current)){
57
+ current[part] = {
58
+ __listeners: []
59
+ } as unknown as FastListeners
60
+ }
61
+ if(i===parts.length-1){
62
+ const node = current[part]
63
+ callback(node,current)
64
+ return node
65
+ }else{
66
+ current = current[part]
67
+ }
68
+ }
69
+ return undefined
70
+ }
71
+
72
+
73
+ /**
74
+ * 从监听器节点中移除指定的事件监听器
75
+ * @private
76
+ * @param node - 监听器节点
77
+ * @param listener - 需要移除的事件监听器
78
+ * @description 遍历节点的监听器列表,移除所有匹配的监听器。支持移除普通函数和数组形式的监听器
79
+ */
80
+ private _removeListener(node: FastListenerNode, path:string[],listener: FastEventListener<any,any,any>): void {
81
+ if(!listener) return
82
+ removeItem(node.__listeners,(item:any)=>{
83
+ item = Array.isArray(item) ? item[0] : item
84
+ const isRemove = item === listener
85
+ if(isRemove && typeof(this._options.onRemoveListener)==='function'){
86
+ this._options.onRemoveListener(path,listener)
87
+ }
88
+ return isRemove
89
+ })
90
+ }
91
+ public on<T extends string>(type: T, listener: FastEventListener<T,Events[T],Meta>, count?:number ): FastEventSubscriber
92
+ public on<T extends Types=Types>(type: T, listener: FastEventListener<Types,Events[T],Meta>, count?:number ): FastEventSubscriber
93
+ public on<P=any>(type: '**', listener: FastEventListener<Types,P,Meta>): FastEventSubscriber
94
+ public on(): FastEventSubscriber{
95
+ const type = arguments[0] as string
96
+ const listener = arguments[1] as FastEventListener
97
+ const count = arguments[2] as number
98
+ if(type.length===0) throw new Error('event type cannot be empty')
99
+
100
+ if(type==='**'){
101
+ return this.onAny(listener)
102
+ }
103
+
104
+ const parts = type.split(this._delimiter);
105
+ const node = this._addListener(parts,listener,count)
106
+
107
+ // Retain不支持通配符
108
+ if(node && !type.includes('*')) this._emitForLastEvent(type)
109
+
110
+ return {
111
+ off: ()=>node && this._removeListener(node,parts,listener)
112
+ }
113
+ }
114
+
115
+ public once<T extends string>(type: T, listener: FastEventListener<T,Events[T],Meta> ): FastEventSubscriber
116
+ public once<T extends Types=Types>(type: T, listener: FastEventListener<Types,Events[T],Meta> ): FastEventSubscriber
117
+ public once(): FastEventSubscriber{
118
+ return this.on(arguments[0],arguments[1],1)
119
+ }
120
+
121
+ /**
122
+ * 注册一个监听器,用于监听所有事件
123
+ * @param listener 事件监听器函数,可以接收任意类型的事件数据
124
+ * @returns {FastEventSubscriber} 返回一个订阅者对象,包含 off 方法用于取消监听
125
+ * @example
126
+ * ```ts
127
+ * const subscriber = emitter.onAny((eventName, data) => {
128
+ * console.log(eventName, data);
129
+ * });
130
+ *
131
+ * // 取消监听
132
+ * subscriber.off();
133
+ * ```
134
+ */
135
+ onAny<P=any>(listener: FastEventListener<string,P,Meta>): FastEventSubscriber {
136
+ const listeners = this.listeners.__listeners
137
+ listeners.push(listener)
138
+ return {
139
+ off:()=>this._removeListener(this.listeners,[],listener)
140
+ }
141
+ }
142
+
143
+ off(listener: FastEventListener<any, any, any>):void
144
+ off(type: string, listener: FastEventListener<any, any, any>):void
145
+ off(type: Types, listener: FastEventListener<any, any, any>):void
146
+ off(type: string):void
147
+ off(type: Types):void
148
+ off(){
149
+ const args = arguments
150
+ const type = typeof(args[0])==='function' ? undefined : args[0]
151
+ const listener = typeof(args[0])==='function' ? args[0] : args[1]
152
+ const parts = type ? type.split(this._delimiter) : []
153
+ const hasWildcard= type ? type.includes('*') : false
154
+ if(type && !hasWildcard){
155
+ this._traverseToPath(this.listeners,parts,(node)=>{
156
+ if(listener){ // 只删除指定的监听器
157
+ this._removeListener(node,parts,listener)
158
+ }else if(type){
159
+ node.__listeners=[]
160
+ }
161
+ })
162
+ }else{ // 仅删除指定的侦听器
163
+ const entryParts:string[] = hasWildcard ? [] : parts
164
+ this._traverseListeners(this.listeners,entryParts,(path,node)=>{
165
+ if(listener!==undefined || (hasWildcard && isPathMatched(path,parts))){
166
+ if(listener){
167
+ this._removeListener(node,parts,listener)
168
+ }else{
169
+ node.__listeners=[]
170
+ }
171
+ }
172
+ })
173
+ }
174
+ }
175
+
176
+ /**
177
+ * 移除所有事件监听器
178
+ * @param entry - 可选的事件前缀,如果提供则只移除指定前缀下的的监听器
179
+ * @description
180
+ * - 如果提供了prefix参数,则只清除该前缀下的所有监听器
181
+ * - 如果没有提供prefix,则清除所有监听器
182
+ * - 同时会清空保留的事件(_retainedEvents)
183
+ * - 重置监听器对象为空
184
+
185
+ * @example
186
+ *
187
+ * ```ts
188
+ * emitter.offAll(); // 清除所有监听器
189
+ * emitter.offAll('a/b'); // 清除a/b下的所有监听器
190
+ *
191
+ */
192
+ offAll(entry?: string) {
193
+ if(entry){
194
+ const entryNode = this._getListenerNode(entry.split(this._delimiter))
195
+ if(entryNode) entryNode.__listeners = []
196
+ this._removeRetainedEvents(entry)
197
+ }else{
198
+ this._retainedEvents.clear()
199
+ this.listeners = { __listeners: [] } as unknown as FastListeners
200
+ }
201
+ }
202
+
203
+ private _getListenerNode(parts:string[]):FastListenerNode | undefined{
204
+ let entryNode: FastListenerNode | undefined
205
+ this._forEachNodes(parts,(node)=>{
206
+ entryNode = node
207
+ })
208
+ return entryNode
209
+ }
210
+ /**
211
+ * 移除保留的事件
212
+ * @param prefix - 事件前缀。如果不提供,将清除所有保留的事件。
213
+ * 如果提供前缀,将删除所有以该前缀开头的事件。
214
+ * 如果前缀不以分隔符结尾,会自动添加分隔符。
215
+ * @private
216
+ */
217
+ private _removeRetainedEvents(prefix?: string) {
218
+ if (!prefix) this._retainedEvents.clear()
219
+ if(prefix?.endsWith(this._delimiter)){
220
+ prefix+=this._delimiter
221
+ }
222
+ this._retainedEvents.delete(prefix!)
223
+ for(let key of this._retainedEvents.keys()){
224
+ if(key.startsWith(prefix!)){
225
+ this._retainedEvents.delete(key)
226
+ }
227
+ }
228
+ }
229
+ clear(){
230
+ this.offAll()
231
+ }
232
+ private _getMeta(extra:Record<string,any>){
233
+ if(!this._options.meta) return extra
234
+ return Object.assign({},this._options.meta,extra) as FastEventMeta<any,any>
235
+ }
236
+ private _emitForLastEvent(type:string){
237
+ if(this._retainedEvents.has(type)){
238
+ const payload = this._retainedEvents.get(type)
239
+ const parts = type.split(this._delimiter);
240
+ this._traverseToPath(this.listeners,parts,(node)=>{
241
+ this._executeListeners(node,payload,this._getMeta({type}))
242
+ })
243
+ // onAny侦听器保存在根节点中,所以需要执行
244
+ this._executeListeners(this.listeners,payload,this._getMeta({type}))
245
+ }
246
+ }
247
+
248
+ /**
249
+ * 遍历监听器节点树
250
+ * @param node 当前遍历的监听器节点
251
+ * @param parts 事件名称按'.'分割的部分数组
252
+ * @param callback 遍历到目标节点时的回调函数
253
+ * @param index 当前遍历的parts数组索引,默认为0
254
+ * @param lastFollowing 当命中**时该值为true, 注意**只能作在路径的最后面,如a.**有效,而a.**.b无效
255
+ * @private
256
+ *
257
+ * 支持三种匹配模式:
258
+ * - 精确匹配: 'a.b.c'
259
+ * - 单层通配: 'a.*.c'
260
+ * - 多层通配: 'a.**'
261
+ */
262
+ private _traverseToPath(node: FastListenerNode, parts: string[], callback: (node: FastListenerNode) => void, index: number = 0, lastFollowing?:boolean): void {
263
+
264
+ if (index >= parts.length) {
265
+ callback(node)
266
+ return
267
+ }
268
+ const part = parts[index]
269
+
270
+ if(lastFollowing===true){
271
+ this._traverseToPath(node, parts, callback, index + 1,true)
272
+ return
273
+ }
274
+
275
+ if (part in node) {
276
+ this._traverseToPath(node[part], parts, callback, index + 1)
277
+ }
278
+
279
+ if ('*' in node) {
280
+ this._traverseToPath(node['*'], parts, callback, index + 1)
281
+ }
282
+ //
283
+ if ('**' in node) {
284
+ this._traverseToPath(node['**'], parts, callback, index + 1,true)
285
+ }
286
+ }
287
+
288
+ private _traverseListeners(node: FastListenerNode, entry:string[], callback: (path:string[],node: FastListenerNode) => void): void {
289
+ let entryNode: FastListenerNode = node
290
+ // 如果指定了entry路径,则按照路径遍历
291
+ if (entry && entry.length > 0) {
292
+ this._traverseToPath(node, entry,(node)=>{
293
+ entryNode= node
294
+ });
295
+ }
296
+ const traverseNodes = (node: FastListenerNode, callback: (path:string[],node: FastListenerNode) => void,parentPath:string[])=>{
297
+ callback(parentPath, node);
298
+ for(let [key,childNode] of Object.entries(node)){
299
+ if(key.startsWith("__")) continue
300
+ if(childNode){
301
+ traverseNodes(childNode as FastListenerNode, callback,[...parentPath,key]);
302
+ }
303
+ }
304
+ }
305
+ // 如果没有指定entry或entry为空数组,则递归遍历所有节点
306
+ traverseNodes(entryNode, callback,[]);
307
+ }
308
+
309
+ private _executeListener(listener:any, payload: any,meta: FastEventMeta<any,any> ):any{
310
+ try{
311
+ if(typeof(listener.__wrappedListener)==='function'){
312
+ return listener.__wrappedListener.call(this._context,payload,meta)
313
+ }else{
314
+ return listener.call(this._context,payload,meta)
315
+ }
316
+ }catch(e:any){
317
+ e._trigger = meta.type
318
+ if(typeof(this._options.onListenerError)==='function'){
319
+ this._options.onListenerError.call(this,meta.type,e)
320
+ }
321
+ // 如果忽略错误,则返回错误对象
322
+ if(this._options.ignoreErrors){
323
+ return e
324
+ }else{
325
+ throw e
326
+ }
327
+ }
328
+ }
329
+
330
+ /**
331
+ * 执行监听器节点中的所有监听函数
332
+ * @param node - FastListenerNode类型的监听器节点
333
+ * @param payload - 事件携带的数据
334
+ * @param type - 事件类型
335
+ * @returns 返回所有监听函数的执行结果数组
336
+ * @private
337
+ *
338
+ * @description
339
+ * 遍历执行节点中的所有监听函数:
340
+ * - 对于普通监听器,直接执行并收集结果
341
+ * - 对于带次数限制的监听器(数组形式),执行后递减次数,当次数为0时移除该监听器
342
+ */
343
+ private _executeListeners(node: FastListenerNode, payload: any, meta: Meta): any[] {
344
+ if (!node || !node.__listeners) return []
345
+ let i = 0
346
+ const listeners = node.__listeners
347
+ let result:any[] = []
348
+ while(i<listeners.length){
349
+ const listener = listeners[i]
350
+ if(Array.isArray(listener)){
351
+ result.push(this._executeListener(listener[0],payload,meta))
352
+ listener[1]--
353
+ if(listener[1]===0) {
354
+ listeners.splice(i,1)
355
+ i-- // 抵消后面的i++
356
+ }
357
+ }else{
358
+ result.push(this._executeListener(listener,payload,meta))
359
+ }
360
+ i++
361
+ }
362
+ return result
363
+ }
364
+
365
+ public emit<R=any>(type:string,payload?:any,retain?:boolean,meta?:Meta):R[]
366
+ public emit<R=any>(type:Types,payload?:Events[Types],retain?:boolean,meta?:Meta):R[]
367
+ public emit<R=any>():R[]{
368
+ const type = arguments[0] as string
369
+ const payload = arguments[1] as any
370
+ const retain = arguments[2] as boolean
371
+ const meta = (arguments[3] || {}) as Meta
372
+
373
+ const parts = type.split(this._delimiter);
374
+ if(retain) {
375
+ this._retainedEvents.set(type,payload)
376
+ }
377
+ const results:any[] = []
378
+ this._traverseToPath(this.listeners,parts,(node)=>{
379
+ results.push(...this._executeListeners(node,payload,this._getMeta({...meta,type})))
380
+ })
381
+ // onAny侦听器保存在根节点中,所以需要执行
382
+ results.push(...this._executeListeners(this.listeners,payload,this._getMeta({...meta,type})))
383
+ return results
384
+ }
385
+
386
+ public async emitAsync<R=any>(type:string,payload?:any,retain?:boolean,meta?:Meta):Promise<[R|Error][]>
387
+ public async emitAsync<R=any>(type:Types,payload?:Events[Types],retain?:boolean,meta?:Meta):Promise<[R|Error][]>
388
+ public async emitAsync<P=any>():Promise<[P|Error][]>{
389
+ const type = arguments[0] as string
390
+ const payload = arguments[1] as any
391
+ const retain = arguments[2] as boolean
392
+ const meta = (arguments[3] || {}) as Meta
393
+
394
+ const results = await Promise.allSettled(this.emit<P>(type,payload,retain,this._getMeta({...meta,type})))
395
+ return results.map((result)=>{
396
+ if(result.status==='fulfilled'){
397
+ return result.value
398
+ }else{
399
+ return result.reason
400
+ }
401
+ })
402
+ }
403
+
404
+ /**
405
+ * 等待指定事件发生
406
+ *
407
+ * @param type
408
+ * @param timeout 超时时间,单位毫秒,默认为 0,表示无限等待
409
+ */
410
+ public waitFor<R=any>(type:string,timeout?:number):Promise<R>
411
+ public waitFor<R=any>(type:Types,timeout?:number):Promise<R>
412
+ public waitFor<R=any>():Promise<R>{
413
+ const type = arguments[0] as string
414
+ const timeout = arguments[1] as number
415
+ return new Promise<R>((resolve,reject)=>{
416
+ let tid:any
417
+ let subscriber:FastEventSubscriber
418
+ const listener = (payload:any)=>{
419
+ clearTimeout(tid)
420
+ subscriber.off()
421
+ resolve(payload)
422
+ }
423
+ if(timeout && timeout>0){
424
+ tid = setTimeout(()=>{
425
+ subscriber && subscriber.off()
426
+ reject(new Error('wait for event<'+ type +'> is timeout'))
427
+ },timeout)
428
+ }
429
+ subscriber = this.on(type,listener)
430
+ })
431
+ }
432
+
433
+ /**
434
+ * 创建事件域
435
+ *
436
+ * 注意:
437
+ *
438
+ * 事件域与当前事件对象共享相同的侦听器表
439
+ * 也就是说,如果在事件域中触发事件,当前事件对象也会触发该事件
440
+ * 两者工不是完全隔离的,仅是事件侦听和触发时的事件类型不同而已
441
+ *
442
+ * const emitter = new FastEvent()
443
+ *
444
+ * const scope= emitter.scope("a/b")
445
+ *
446
+ * scope.on("x",()=>{}) == emitter.on("a/b/x",()=>{})
447
+ * scope.emit("x",1) == emitter.emit("a/b/x",1)
448
+ * scope.offAll() == emitter.offAll("a/b")
449
+ *
450
+ */
451
+ scope<T extends string>(prefix:T){
452
+ return new FastEventScope<ScopeEvents<Events,T>>(this as unknown as FastEvent<ScopeEvents<Events,T>>,prefix)
453
+ }
454
+
455
+ }
package/src/index.ts CHANGED
@@ -1 +1,3 @@
1
- export * from "./event"
1
+ export * from "./event"
2
+ export * from "./scope"
3
+ export * from "./types"