createCallbacks
Functions
createCallbacks()
createCallbacks<
T
>():Object
创建回调管理器
Type parameters
Parameter |
---|
T extends AnyFn |
Returns
Object
addadd: (
handler
,prepend
?) => () =>void
添加回调句柄,若句柄已存在则忽略
Parameters
Parameter Type Description handler
T
回调句柄 prepend
?boolean
是否为前置添加 Returns
Function
移除回调句柄
Returns
void
Example
tsconst callbacks = createCallbacks() const remove = callbacks.add(() => { console.log('callback run') }) remove()
addOnceaddOnce: (
handler
,prepend
?) => () =>void
添加单次回调句柄
Parameters
Parameter Type Description handler
T
回调句柄 prepend
?boolean
是否为前置添加 Returns
Function
移除回调句柄
Returns
void
Example
tsconst callbacks = createCallbacks() const remove = callbacks.addOnce(() => { console.log('callback run') }) remove()
hashas: (
handler
) =>boolean
判断回调句柄是否已注册
Parameters
Parameter Type Description handler
T
回调句柄 Returns
boolean
Example
tsconst callbacks = createCallbacks() const handler = () => { console.log('callback run') } callbacks.add(handler) callbacks.has(handler) // => true
listlist: () =>
T
[]获取回调句柄列表(副本)
Returns
T
[]回调句柄列表
removeremove: (
callback
) =>void
移除回调句柄
Parameters
Parameter Type Description callback
T
回调句柄 Returns
void
Example
tsconst callbacks = createCallbacks() const handler = () => { console.log('callback run') } callbacks.add(handler) remove(handler)
resetreset: () =>
void
清空回调句柄
Returns
void
runrun: (...
args
) =>CallbackReturn
[]运行全部回调句柄
Parameters
Parameter Type Description ... args
Parameters
<T
>回调参数 Returns
CallbackReturn
[]回调结果列表
Example
tsconst callbacks = createCallbacks() callbacks.add((value: number) => value * 2) callbacks.add((value: number) => value / 2) callbacks.add((value: number) => value % 2) callbacks.run(10) // => [20, 5, 0]
Deprecated
推荐使用 createEventHook()
!
Example
ts
const callbacks = createCallbacks()
const handler = () => console.log('callback run')
// add
callbacks.add(handler)
// remove
callbacks.remove(handler)
// run
callbacks.run()
// list
callbacks.list()
// => [handler]
// reset
callbacks.reset()
callbacks.list()
// => []