Skip to content

Commit e756f2d

Browse files
committed
onDestroy for ssr
1 parent dfbec6e commit e756f2d

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

packages/svelte/src/internal/server/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ export function assign_payload(p1, p2) {
7979
p1.anchor = p2.anchor;
8080
}
8181

82+
/**
83+
* Array of `onDestroy` callbacks that should be called at the end of the server render function
84+
* @type {Function[]}
85+
*/
86+
export let on_destroy = [];
87+
8288
/**
8389
* @param {(...args: any[]) => void} component
8490
* @param {{ props: Record<string, any>; context?: Map<any, any> }} options
@@ -90,6 +96,8 @@ export function render(component, options) {
9096
const root_head_anchor = create_anchor(payload.head);
9197

9298
set_is_ssr(true);
99+
const prev_on_destroy = on_destroy;
100+
on_destroy = [];
93101
payload.out += root_anchor;
94102

95103
if (options.context) {
@@ -102,6 +110,8 @@ export function render(component, options) {
102110
$.pop();
103111
}
104112
payload.out += root_anchor;
113+
for (const cleanup of on_destroy) cleanup();
114+
on_destroy = prev_on_destroy;
105115
set_is_ssr(false);
106116

107117
return {

packages/svelte/src/main/main-server.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { on_destroy } from '../internal/server/index.js';
2+
13
export {
24
createRoot,
35
createEventDispatcher,
@@ -6,7 +8,6 @@ export {
68
getContext,
79
hasContext,
810
mount,
9-
onDestroy,
1011
setContext,
1112
tick,
1213
untrack
@@ -15,6 +16,11 @@ export {
1516
/** @returns {void} */
1617
export function onMount() {}
1718

19+
/** @param {Function} fn */
20+
export function onDestroy(fn) {
21+
on_destroy.push(fn);
22+
}
23+
1824
/** @returns {void} */
1925
export function beforeUpdate() {}
2026

0 commit comments

Comments
 (0)