类继承
FastEvent
提供了FastEvent
和FastEventScope
两个类,除了独立创建实例外,也可以通过继承的方式创建。
继承FastEvent
ts
import { FastEvent, FastEventOptions } from 'fastevent'
interface MyEventOptions extends FastEventOptions {
count?: number
}
class MyEvent extends FastEvent {
constructor(options?: Partial<MyEventOptions>) {
super(Object.assign({}, options))
}
get options() {
return super.options as MyEventOptions
}
}
const emitter = new MyEvent()
emitter.on('test', function (this, message) {
type This = typeof this
})
type OptionsType = typeof emitter.options
emitter.options.count = 100
- 以上
MyEvent
继承了FastEvent
,并且重载了Options
选项。
当创建FastEvent
实例时,如何传入context
参数,则情况有些不一样。
ts
import { FastEvent, FastEventOptions } from 'fastevent'
interface MyEventOptions extends FastEventOptions {
count?: number
}
class MyEvent extends FastEvent {
constructor(options?: Partial<MyEventOptions>) {
super(Object.assign({}, options))
}
}
const emitter = new MyEvent({
context: { a: 1 } as never
})
emitter.on('test', function (this, message) {
type This = typeof this
// This !== {a:1}
// This == MyEvent
})
type OptionsType = typeof emitter.options
上例中,为什么监听器函数的this
实际指向的是{a:1}
,但是类型却不是{a:1}
呢?
因为MyEvent
虽然继承了FastEvent
,但是由于context
是一个泛型参数,没有传递给FastEvent
,导致context=never
。
所以需要修改如下:
ts
import { FastEvent, FastEventOptions } from 'fastevent'
interface MyEventOptions<M, C> extends FastEventOptions<M, C> {
count?: number
}
class MyEvent<E extends Record<string, any> = Record<string, any>,
M extends Record<string, any> = Record<string, any>,
C = never
> extends FastEvent<E, M, C> {
constructor(options?: Partial<MyEventOptions<M, C>>) {
super(Object.assign({}, options))
}
get options() {
return super.options as MyEventOptions<M, C>
}
}
const emitter = new MyEvent({
context: { a: 1 }
})
emitter.on('test', function (this, message) {
type This = typeof this
// This === {a:1}
})
type OptionsType = typeof emitter.options
emitter.options.count = 100
继承FastEventScope
FastEventScope
的继承方式与FastEvent
基本类似。
ts
import {
FastEvent,
FastEventScope,
FastEventScopeOptions,OverrideOptions
} from 'fastevent'
type MyScopeEvents = {
a: number
b: string
c: boolean
}
interface MyScopeOptions<M, C> extends FastEventScopeOptions<M, C> {
count?: number
}
const emitter = new FastEvent({
meta: {
root: 100
}
})
class MyScope<E extends Record<string, any> = MyScopeEvents,
M extends Record<string, any> = Record<string, any>,
C = never
> extends FastEventScope<E, M, C> {
constructor(options?: Partial<MyScopeOptions<M, C>>) {
super(Object.assign({}, options))
}
test(value: number) {
return 100
}
get options() {
return super.options as MyScopeOptions<M, C>
}
}
const myScope = emitter.scope('modules/my', new MyScope())
myScope.on('a', function (this,message) {
type This = typeof this
message.meta
message.type
message.payload
})