11/* eslint-disable dci-lint/atomic-role-binding */
22import type { TaintedFields , SuperFormValidated , SuperValidated } from '$lib/superValidate.js' ;
3- import type { ActionResult , Page , SubmitFunction } from '@sveltejs/kit' ;
3+ import type { ActionResult , BeforeNavigate , Page , SubmitFunction } from '@sveltejs/kit' ;
44import {
55 derived ,
66 get ,
@@ -383,6 +383,28 @@ try {
383383 // No Storybook
384384}
385385
386+ const onDestroyCallbacks = new Set < ( ) => void > ( ) ;
387+ const beforeNavigateCallbacks = new Set < ( nav : BeforeNavigate ) => Promise < void > > ( ) ;
388+ let lifeCycleHandlersInited = false ;
389+ function initLifeCycleCallbacks ( ) {
390+ if ( lifeCycleHandlersInited ) return ;
391+ lifeCycleHandlersInited = true ;
392+
393+ onDestroy ( ( ) => {
394+ for ( const callback of onDestroyCallbacks ) {
395+ callback ( ) ;
396+ }
397+ onDestroyCallbacks . clear ( ) ;
398+ } ) ;
399+
400+ beforeNavigate ( ( nav : BeforeNavigate ) => {
401+ for ( const callback of beforeNavigateCallbacks ) {
402+ callback ( nav ) ;
403+ }
404+ beforeNavigateCallbacks . clear ( ) ;
405+ } ) ;
406+ }
407+
386408/////////////////////////////////////////////////////////////////////
387409
388410/**
@@ -404,6 +426,8 @@ export function superForm<
404426 // To check if a full validator is used when switching options.validators dynamically
405427 let initialValidator : FormOptions < T , M , In > [ 'validators' ] | undefined = undefined ;
406428
429+ initLifeCycleCallbacks ( ) ;
430+
407431 {
408432 if ( options . legacy ?? LEGACY_MODE ) {
409433 if ( options . resetForm === undefined ) options . resetForm = false ;
@@ -518,7 +542,7 @@ export function superForm<
518542
519543 ///// From here, form is properly initialized /////
520544
521- onDestroy ( ( ) => {
545+ onDestroyCallbacks . add ( ( ) => {
522546 Unsubscriptions_unsubscribe ( ) ;
523547 NextChange_clear ( ) ;
524548 EnhancedForm_destroy ( ) ;
@@ -1350,7 +1374,7 @@ export function superForm<
13501374 // Tainted check
13511375 const defaultMessage = 'Leave page? Changes that you made may not be saved.' ;
13521376 let forceRedirection = false ;
1353- beforeNavigate ( async ( nav ) => {
1377+ beforeNavigateCallbacks . add ( async ( nav : BeforeNavigate ) => {
13541378 if ( options . taintedMessage && ! Data . submitting && ! forceRedirection ) {
13551379 if ( Tainted_isTainted ( ) ) {
13561380 const { taintedMessage } = options ;
0 commit comments