-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
22 additions
and
81 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,62 +1,32 @@ | ||
/* eslint-disable lines-between-class-members */ | ||
/* eslint-disable no-dupe-class-members */ | ||
import { randomString } from './randomString' | ||
import { isFunction } from './isFunction' | ||
|
||
export type Dispose = () => void | ||
|
||
const anonymousKey: string = `__anonymous_${randomString()}__` | ||
export type DisposerItem = () => void | ||
|
||
/** | ||
* 处置器。 | ||
* 资源释放器。 | ||
*/ | ||
export class Disposer<N extends string | number = string | number> { | ||
export class Disposer { | ||
/** | ||
* 待处置项目存放容器。 | ||
*/ | ||
private jar: { [name in N]: Dispose[] } = Object.create(null) | ||
|
||
/** | ||
* 将待处置项目加入容器。 | ||
* | ||
* @param name 待处置项目名称 | ||
* @param dispose 处置行为 | ||
* 待释放项目存储容器。 | ||
*/ | ||
public add(name: N, dispose: Dispose | Dispose[]): void | ||
/** | ||
* 将匿名待处置项目加入容器。 | ||
* | ||
* @param dispose 处置行为 | ||
*/ | ||
public add(dispose: Dispose | Dispose[]): void | ||
public add(name: any, dispose?: any): void { | ||
if (dispose == null) { | ||
dispose = name | ||
name = anonymousKey | ||
} | ||
dispose = Array.isArray(dispose) ? dispose : [dispose] | ||
;(this.jar as any)[name] = [ | ||
...((this.jar as any)[name] || []), | ||
...dispose, | ||
] | ||
} | ||
private jar: DisposerItem[] = [] | ||
|
||
/** | ||
* 处置项目。 | ||
* 新增待释放项目。 | ||
* | ||
* @param name 欲处置项目名称,不设置表示匿名项目 | ||
* @param items 待释放项目的序列 | ||
*/ | ||
public dispose(name?: N): void { | ||
name = name != null ? name : anonymousKey as any | ||
(this.jar[name] || /* istanbul ignore next */ []).forEach(dispose => dispose()) | ||
delete this.jar[name] | ||
public add(...items: DisposerItem[]): void { | ||
this.jar.push(...items) | ||
} | ||
|
||
/** | ||
* 处置所有未处置项目。 | ||
* 释放所有项目。 | ||
*/ | ||
public disposeAll(): void { | ||
for (const key in this.jar) { | ||
this.dispose(key) | ||
} | ||
public dispose() { | ||
this.jar.forEach( | ||
item => isFunction(item) && item(), | ||
) | ||
this.jar = [] | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters