程序生命周期

Deno 支持浏览器兼容的生命周期事件: loadunload。你可以使用 这些事件在你的程序中提供用于安装和清理的代码。

load 事件的监听器可以是异步的,并且将被等待。unload 事件的监听器则需要是同步的。这两种事件都不能被取消。

示例:

main.ts

import "./imported.ts";

const handler = (e: Event): void => {
  console.log(`got ${e.type} event in event handler (main)`);
};

globalThis.addEventListener("load", handler);

globalThis.addEventListener("unload", handler);

globalThis.onload = (e: Event): void => {
  console.log(`got ${e.type} event in onload function (main)`);
};

globalThis.onunload = (e: Event): void => {
  console.log(`got ${e.type} event in onunload function (main)`);
};

console.log("log from main script");

imported.ts

const handler = (e: Event): void => {
  console.log(`got ${e.type} event in event handler (imported)`);
};

globalThis.addEventListener("load", handler);
globalThis.addEventListener("unload", handler);

globalThis.onload = (e: Event): void => {
  console.log(`got ${e.type} event in onload function (imported)`);
};

globalThis.onunload = (e: Event): void => {
  console.log(`got ${e.type} event in onunload function (imported)`);
};

console.log("log from imported script");

A couple notes on this example:

$ deno run main.ts
log from imported script
log from main script
got load event in event handler (imported)
got load event in event handler (main)
got load event in onload function (main)
got unload event in event handler (imported)
got unload event in event handler (main)
got unload event in onunload function (main)

所有通过 addEventListener 添加的侦听器都会运行, 但是在 main.ts 文件里定义的 onloadonunload 覆盖了在 imported.ts 定义的处理程序。

换句话说, 你可以可以使用 addEventListener 注册多个 "load""unload" 事件, 但是,只有最后加载的 onloadonunload 事件处理程序会执行。因此,在可能的情况下,最好是使用 addEventListener