zhangjian
2023-06-05 0976d2d0f90cff460cedfdc8bd74e98c2c31a58c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { Dictionary, WithThisType } from './types';
 
// Return true to cancel bubble
export type EventCallbackSingleParam<EvtParam = any> = EvtParam extends any
    ? (params: EvtParam) => boolean | void
    : never
 
export type EventCallback<EvtParams = any[]> = EvtParams extends any[]
    ? (...args: EvtParams) => boolean | void
    : never
export type EventQuery = string | Object
 
type CbThis<Ctx, Impl> = unknown extends Ctx ? Impl : Ctx;
 
type EventHandler<Ctx, Impl, EvtParams> = {
    h: EventCallback<EvtParams>
    ctx: CbThis<Ctx, Impl>
    query: EventQuery
 
    callAtLast: boolean
}
 
type DefaultEventDefinition = Dictionary<EventCallback<any[]>>;
 
export interface EventProcessor<EvtDef = DefaultEventDefinition> {
    normalizeQuery?: (query: EventQuery) => EventQuery
    filter?: (eventType: keyof EvtDef, query: EventQuery) => boolean
    afterTrigger?: (eventType: keyof EvtDef) => void
}
 
/**
 * Event dispatcher.
 *
 * Event can be defined in EvtDef to enable type check. For example:
 * ```ts
 * interface FooEvents {
 *     // key: event name, value: the first event param in `trigger` and `callback`.
 *     myevent: {
 *        aa: string;
 *        bb: number;
 *     };
 * }
 * class Foo extends Eventful<FooEvents> {
 *     fn() {
 *         // Type check of event name and the first event param is enabled here.
 *         this.trigger('myevent', {aa: 'xx', bb: 3});
 *     }
 * }
 * let foo = new Foo();
 * // Type check of event name and the first event param is enabled here.
 * foo.on('myevent', (eventParam) => { ... });
 * ```
 *
 * @param eventProcessor The object eventProcessor is the scope when
 *        `eventProcessor.xxx` called.
 * @param eventProcessor.normalizeQuery
 *        param: {string|Object} Raw query.
 *        return: {string|Object} Normalized query.
 * @param eventProcessor.filter Event will be dispatched only
 *        if it returns `true`.
 *        param: {string} eventType
 *        param: {string|Object} query
 *        return: {boolean}
 * @param eventProcessor.afterTrigger Called after all handlers called.
 *        param: {string} eventType
 */
export default class Eventful<EvtDef extends DefaultEventDefinition = DefaultEventDefinition> {
 
    private _$handlers: Dictionary<EventHandler<any, any, any[]>[]>
 
    protected _$eventProcessor: EventProcessor<EvtDef>
 
    constructor(eventProcessors?: EventProcessor<EvtDef>) {
        if (eventProcessors) {
            this._$eventProcessor = eventProcessors;
        }
    }
 
    on<Ctx, EvtNm extends keyof EvtDef>(
        event: EvtNm,
        handler: WithThisType<EvtDef[EvtNm], CbThis<Ctx, this>>,
        context?: Ctx
    ): this
    on<Ctx, EvtNm extends keyof EvtDef>(
        event: EvtNm,
        query: EventQuery,
        handler: WithThisType<EvtDef[EvtNm], CbThis<Ctx, this>>,
        context?: Ctx
    ): this
    /**
     * Bind a handler.
     *
     * @param event The event name.
     * @param Condition used on event filter.
     * @param handler The event handler.
     * @param context
     */
    on<Ctx, EvtNm extends keyof EvtDef>(
        event: EvtNm,
        query: EventQuery | WithThisType<EventCallback<EvtDef[EvtNm]>, CbThis<Ctx, this>>,
        handler?: WithThisType<EventCallback<EvtDef[EvtNm]>, CbThis<Ctx, this>> | Ctx,
        context?: Ctx
    ): this {
        if (!this._$handlers) {
            this._$handlers = {};
        }
 
        const _h = this._$handlers;
 
        if (typeof query === 'function') {
            context = handler as Ctx;
            handler = query as (...args: any) => any;
            query = null;
        }
 
        if (!handler || !event) {
            return this;
        }
 
        const eventProcessor = this._$eventProcessor;
        if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
            query = eventProcessor.normalizeQuery(query);
        }
 
        if (!_h[event as string]) {
            _h[event as string] = [];
        }
 
        for (let i = 0; i < _h[event as string].length; i++) {
            if (_h[event as string][i].h === handler) {
                return this;
            }
        }
 
        const wrap: EventHandler<Ctx, this, unknown[]> = {
            h: handler as EventCallback<unknown[]>,
            query: query,
            ctx: (context || this) as CbThis<Ctx, this>,
            // FIXME
            // Do not publish this feature util it is proved that it makes sense.
            callAtLast: (handler as any).zrEventfulCallAtLast
        };
 
        const lastIndex = _h[event as string].length - 1;
        const lastWrap = _h[event as string][lastIndex];
        (lastWrap && lastWrap.callAtLast)
            ? _h[event as string].splice(lastIndex, 0, wrap)
            : _h[event as string].push(wrap);
 
        return this;
    }
 
    /**
     * Whether any handler has bound.
     */
    isSilent(eventName: keyof EvtDef): boolean {
        const _h = this._$handlers;
        return !_h || !_h[eventName as string] || !_h[eventName as string].length;
    }
 
    /**
     * Unbind a event.
     *
     * @param eventType The event name.
     *        If no `event` input, "off" all listeners.
     * @param handler The event handler.
     *        If no `handler` input, "off" all listeners of the `event`.
     */
    off(eventType?: keyof EvtDef, handler?: Function): this {
        const _h = this._$handlers;
 
        if (!_h) {
            return this;
        }
 
        if (!eventType) {
            this._$handlers = {};
            return this;
        }
 
        if (handler) {
            if (_h[eventType as string]) {
                const newList = [];
                for (let i = 0, l = _h[eventType as string].length; i < l; i++) {
                    if (_h[eventType as string][i].h !== handler) {
                        newList.push(_h[eventType as string][i]);
                    }
                }
                _h[eventType as string] = newList;
            }
 
            if (_h[eventType as string] && _h[eventType as string].length === 0) {
                delete _h[eventType as string];
            }
        }
        else {
            delete _h[eventType as string];
        }
 
        return this;
    }
 
    /**
     * Dispatch a event.
     *
     * @param {string} eventType The event name.
     */
    trigger<EvtNm extends keyof EvtDef>(
        eventType: EvtNm,
        ...args: Parameters<EvtDef[EvtNm]>
    ): this {
        if (!this._$handlers) {
            return this;
        }
 
        const _h = this._$handlers[eventType as string];
        const eventProcessor = this._$eventProcessor;
 
        if (_h) {
            const argLen = args.length;
 
            const len = _h.length;
            for (let i = 0; i < len; i++) {
                const hItem = _h[i];
                if (eventProcessor
                    && eventProcessor.filter
                    && hItem.query != null
                    && !eventProcessor.filter(eventType, hItem.query)
                ) {
                    continue;
                }
 
                // Optimize advise from backbone
                switch (argLen) {
                    case 0:
                        hItem.h.call(hItem.ctx);
                        break;
                    case 1:
                        hItem.h.call(hItem.ctx, args[0]);
                        break;
                    case 2:
                        hItem.h.call(hItem.ctx, args[0], args[1]);
                        break;
                    default:
                        // have more than 2 given arguments
                        hItem.h.apply(hItem.ctx, args);
                        break;
                }
            }
        }
 
        eventProcessor && eventProcessor.afterTrigger
            && eventProcessor.afterTrigger(eventType);
 
        return this;
    }
 
    /**
     * Dispatch a event with context, which is specified at the last parameter.
     *
     * @param {string} type The event name.
     */
    triggerWithContext(type: keyof EvtDef, ...args: any[]): this {
        if (!this._$handlers) {
            return this;
        }
 
        const _h = this._$handlers[type as string];
        const eventProcessor = this._$eventProcessor;
 
        if (_h) {
            const argLen = args.length;
            const ctx = args[argLen - 1];
 
            const len = _h.length;
            for (let i = 0; i < len; i++) {
                const hItem = _h[i];
                if (eventProcessor
                    && eventProcessor.filter
                    && hItem.query != null
                    && !eventProcessor.filter(type, hItem.query)
                ) {
                    continue;
                }
 
                // Optimize advise from backbone
                switch (argLen) {
                    case 0:
                        hItem.h.call(ctx);
                        break;
                    case 1:
                        hItem.h.call(ctx, args[0]);
                        break;
                    case 2:
                        hItem.h.call(ctx, args[0], args[1]);
                        break;
                    default:
                        // have more than 2 given arguments
                        hItem.h.apply(ctx, args.slice(1, argLen - 1));
                        break;
                }
            }
        }
 
        eventProcessor && eventProcessor.afterTrigger
            && eventProcessor.afterTrigger(type);
 
        return this;
    }
 
}