Skip to content

createCallbacks

Functions

createCallbacks()

createCallbacks<T>(): Object

创建回调管理器

Type parameters

Parameter
T extends AnyFn

Returns

Object

add

add: (handler, prepend?) => () => void

添加回调句柄,若句柄已存在则忽略

Parameters
ParameterTypeDescription
handlerT回调句柄
prepend?boolean是否为前置添加
Returns

Function

移除回调句柄

Returns

void

Example
ts
const callbacks = createCallbacks()
const remove = callbacks.add(() => {
console.log('callback run')
})
remove()
addOnce

addOnce: (handler, prepend?) => () => void

添加单次回调句柄

Parameters
ParameterTypeDescription
handlerT回调句柄
prepend?boolean是否为前置添加
Returns

Function

移除回调句柄

Returns

void

Example
ts
const callbacks = createCallbacks()
const remove = callbacks.addOnce(() => {
console.log('callback run')
})
remove()
has

has: (handler) => boolean

判断回调句柄是否已注册

Parameters
ParameterTypeDescription
handlerT回调句柄
Returns

boolean

Example
ts
const callbacks = createCallbacks()
const handler = () => {
console.log('callback run')
}
callbacks.add(handler)

callbacks.has(handler)
// => true
list

list: () => T[]

获取回调句柄列表(副本)

Returns

T[]

回调句柄列表

remove

remove: (callback) => void

移除回调句柄

Parameters
ParameterTypeDescription
callbackT回调句柄
Returns

void

Example
ts
const callbacks = createCallbacks()
const handler = () => {
console.log('callback run')
}
callbacks.add(handler)

remove(handler)
reset

reset: () => void

清空回调句柄

Returns

void

run

run: (...args) => CallbackReturn[]

运行全部回调句柄

Parameters
ParameterTypeDescription
...argsParameters<T>回调参数
Returns

CallbackReturn[]

回调结果列表

Example
ts
const 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()
// => []