Skip to content
This repository has been archived by the owner on Nov 27, 2023. It is now read-only.

Commit

Permalink
feat: allow to remove lifecycle listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
KnisterPeter committed Oct 11, 2020
1 parent f884ba4 commit 659bee1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
32 changes: 32 additions & 0 deletions lib/__tests__/remove-lifecycle-listener-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// tslint:disable: no-implicit-dependencies
import { assert } from 'chai';
import { TSDI, component } from '..';

describe('TSDI', () => {
let tsdi: TSDI;

beforeEach(() => {
tsdi = new TSDI();
});

afterEach(() => {
tsdi.close();
});
it('should allow to remove lifecycle listeners', () => {
@component
class Component {}
tsdi.register(Component);

const removeLifecycleListener = tsdi.addLifecycleListener({
onCreate(comp: any): void {
if (comp instanceof Component) {
assert.fail();
}
},
});

removeLifecycleListener();

tsdi.get(Component);
});
});
11 changes: 10 additions & 1 deletion lib/tsdi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,20 @@ export class TSDI {
this.parent = parent;
}

public addLifecycleListener(lifecycleListener: LifecycleListener): void {
public addLifecycleListener(
lifecycleListener: LifecycleListener
): () => void {
this.lifecycleListeners.push(lifecycleListener);
Object.keys(this.instances).forEach((idx) =>
this.notifyOnCreate(this.instances[parseInt(idx, 10)])
);

return () => {
const idx = this.lifecycleListeners.findIndex(
(l) => l === lifecycleListener
);
this.lifecycleListeners.splice(idx, 1);
};
}

private notifyOnCreate(component: any): void {
Expand Down

0 comments on commit 659bee1

Please sign in to comment.