Skip to content

Commit

Permalink
fix: make onEvent return a method for removing the listener
Browse files Browse the repository at this point in the history
  • Loading branch information
nytamin committed Sep 3, 2019
1 parent 0322313 commit d877d24
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/__tests__/test.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,16 @@ const getTests = (disableMultithreading: boolean) => {

let threaded = await threadedClass<House>(HOUSE_PATH, House, [['north', 'west'], ['south']], { disableMultithreading })
let onClosed = jest.fn()
ThreadedClassManager.onEvent(threaded, 'thread_closed', onClosed)
const onClosedListener = ThreadedClassManager.onEvent(threaded, 'thread_closed', onClosed)

expect(await threaded.getWindows('')).toHaveLength(2)
expect(await threaded.getRooms()).toHaveLength(1)

await ThreadedClassManager.destroy(threaded)
expect(ThreadedClassManager.getThreadCount()).toEqual(0)

onClosedListener.stop()

expect(onClosed).toHaveBeenCalledTimes(1)
})
test('import own basic class', async () => {
Expand Down
10 changes: 8 additions & 2 deletions src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,21 @@ export class ThreadedClassManagerClass {
return this._internal.getChildrenCount()
}
public onEvent (proxy: ThreadedClass<any>, event: string, cb: Function) {
this._internal.on(event, (child: Child) => {
const onEvent = (child: Child) => {
let foundChild = Object.keys(child.instances).find((instanceId) => {
const instance = child.instances[instanceId]
return instance.proxy === proxy
})
if (foundChild) {
cb()
}
})
}
this._internal.on(event, onEvent)
return {
stop: () => {
this._internal.removeListener(event, onEvent)
}
}
}
/**
* Restart the thread of the proxy instance
Expand Down

0 comments on commit d877d24

Please sign in to comment.