Skip to content

Commit d3e7043

Browse files
committed
fix(decorator): do not override props with same name
Now every property is stored on it's own object instance that is hidden from enumeration
1 parent c8756b0 commit d3e7043

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

__tests__/decorator.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { EMPTY, Subject } from 'rxjs';
1+
import { EMPTY, Observable, Subject } from 'rxjs';
22

33
import { WithUntilDestroyed } from '../src/decorator';
44
import * as untilDestroyedObj from '../src/take-until-destroy';
@@ -58,4 +58,18 @@ describe('@WithUntilDestroyed decorator', () => {
5858

5959
expect(callback).not.toHaveBeenCalled();
6060
});
61+
62+
it('should not share value between instances', () => {
63+
class Test {
64+
@WithUntilDestroyed()
65+
stream$ = new Observable();
66+
67+
ngOnDestroy() {}
68+
}
69+
70+
const t1 = new Test();
71+
const t2 = new Test();
72+
73+
expect(t1.stream$).not.toBe(t2.stream$);
74+
});
6175
});

src/decorator.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,22 @@ import { untilDestroyed } from './take-until-destroy';
2121
*
2222
* Do not forget to implement {@link OnDestroy} life-cycle hook.
2323
*/
24-
export function WithUntilDestroyed(
25-
destroyMethodName?: string,
26-
): PropertyDecorator {
27-
return (target, propKey) => {
28-
let val: Observable<any>;
24+
export function WithUntilDestroyed(destroyMethodName?: string): PropertyDecorator {
25+
return function(target, propKey) {
26+
const valKey = `__WithUntilDestroyed:${String(propKey)}__`;
2927

3028
function getter() {
31-
return val;
29+
return this[valKey];
3230
}
3331

3432
function setter(newVal) {
3533
if (isObservable(newVal)) {
36-
val = newVal.pipe(untilDestroyed(this, destroyMethodName));
34+
delete this[valKey];
35+
Object.defineProperty(this, valKey, {
36+
configurable: true,
37+
enumerable: false,
38+
value: newVal.pipe(untilDestroyed(this, destroyMethodName)),
39+
});
3740
} else {
3841
throw Error(
3942
`WithUntilDestroyed: Property ${String(propKey)} on ${

0 commit comments

Comments
 (0)