Skip to content

Commit

Permalink
feat(dirty-check): pass window object in config
Browse files Browse the repository at this point in the history
  • Loading branch information
FFKL committed Sep 10, 2021
1 parent 944447a commit 16c4a1b
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions libs/dirty-check-forms/src/lib/dirty-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { equal as isEqual } from './is-equal';
interface DirtyCheckConfig {
debounce?: number;
withDisabled?: boolean;
window?: Window;
}

function mergeConfig(config: DirtyCheckConfig): DirtyCheckConfig {
Expand All @@ -38,7 +39,7 @@ export function dirtyCheck<U>(
source: Observable<U>,
config: DirtyCheckConfig = {}
): Observable<boolean> {
const { debounce, withDisabled } = mergeConfig(config);
const { debounce, withDisabled, window } = mergeConfig(config);
const value = () => getControlValue(control, withDisabled);
const valueChanges$ = merge(
defer(() => of(value())),
Expand All @@ -59,16 +60,18 @@ export function dirtyCheck<U>(
shareReplay({ bufferSize: 1, refCount: true })
);

observer.add(
fromEvent(window, 'beforeunload')
.pipe(withLatestFrom(isDirty$))
.subscribe(([event, isDirty]) => {
if (isDirty) {
event.preventDefault();
event.returnValue = false;
}
})
);
if (window) {
observer.add(
fromEvent(window, 'beforeunload')
.pipe(withLatestFrom(isDirty$))
.subscribe(([event, isDirty]) => {
if (isDirty) {
event.preventDefault();
event.returnValue = false;
}
})
);
}

return isDirty$.subscribe(observer);
});
Expand Down

0 comments on commit 16c4a1b

Please # to comment.