Skip to content

Commit

Permalink
feat(Disposer): 支持匿名项目
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 27, 2019
1 parent 95aa275 commit ce65345
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
32 changes: 24 additions & 8 deletions src/Disposer.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,54 @@
export type DisposerItemName = string | number
/* eslint-disable lines-between-class-members */
/* eslint-disable no-dupe-class-members */
import randomString from './randomString'

export type Dispose = () => void

const anonymousKey: string = `__anonymous_${randomString()}__`

/**
* 处置器。
*/
export default class Disposer {
export default class Disposer<N extends string | number = string | number> {
/**
* 待处置项目存放容器。
*
* @private
*/
private jar: { [name: string]: Dispose[] } = Object.create(null)
private jar: { [name in N]: Dispose[] } = Object.create(null)

/**
* 将待处置项目加入容器。
*
* @param name 待处置项目名称
* @param dispose 处置行为
*/
public add(name: DisposerItemName, dispose: Dispose | Dispose[]): void {
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[name] = [
...(this.jar[name] || []),
;(this.jar as any)[name] = [
...((this.jar as any)[name] || []),
...dispose,
]
}

/**
* 处置项目。
*
* @param name 欲处置项目名称
* @param [name] 欲处置项目名称,不设置表示匿名项目
*/
public dispose(name: DisposerItemName): void {
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]
}
Expand Down
12 changes: 12 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,18 @@ describe('Disposer', () => {
expect(dispose3.calledOnce).toBeTruthy()
expect((disposer as any).jar).toEqual({})
})
test('匿名项目', () => {
const dispose1 = sinon.fake()
const dispose2 = sinon.fake()
const dispose3 = sinon.fake()
disposer.add(dispose1)
disposer.add([dispose2, dispose3])
disposer.dispose()
expect(dispose1.calledOnce).toBeTruthy()
expect(dispose2.calledOnce).toBeTruthy()
expect(dispose3.calledOnce).toBeTruthy()
expect((disposer as any).jar).toEqual({})
})
})

describe('inBrowser', () => {
Expand Down

0 comments on commit ce65345

Please sign in to comment.