程序生命周期

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

load 事件的侦听器 (listener) 可以是异步 (async) 的,将被等待 (await)。unload 事件的监听器需要是同步的。这两项事件都不能被取消。

示例:

main.ts

  1. import "./imported.ts";
  2. const handler = (e: Event): void => {
  3. console.log(`got ${e.type} event in event handler (main)`);
  4. };
  5. window.addEventListener("load", handler);
  6. window.addEventListener("unload", handler);
  7. window.onload = (e: Event): void => {
  8. console.log(`got ${e.type} event in onload function (main)`);
  9. };
  10. window.onunload = (e: Event): void => {
  11. console.log(`got ${e.type} event in onunload function (main)`);
  12. };
  13. console.log("log from main script");

imported.ts

  1. const handler = (e: Event): void => {
  2. console.log(`got ${e.type} event in event handler (imported)`);
  3. };
  4. window.addEventListener("load", handler);
  5. window.addEventListener("unload", handler);
  6. window.onload = (e: Event): void => {
  7. console.log(`got ${e.type} event in onload function (imported)`);
  8. };
  9. window.onunload = (e: Event): void => {
  10. console.log(`got ${e.type} event in onunload function (imported)`);
  11. };
  12. console.log("log from imported script");

注意,您可以同时使用 window.addEventListenerwindow.onload / window.onunload 来定义事件的处理程序。它们之间有一个主要的区别,让我们运行示例:

  1. $ deno run main.ts
  2. log from imported script
  3. log from main script
  4. got load event in onload function (main)
  5. got load event in event handler (imported)
  6. got load event in event handler (main)
  7. got unload event in onunload function (main)
  8. got unload event in event handler (imported)
  9. got unload event in event handler (main)

所有通过 window.addEventListener 添加的侦听器都被运行,但是在 main.ts 中定义的 window.onloadwindow.onunload 覆盖了 imported.ts 中定义的处理程序。

换句话说,您可以注册多个 window.addEventListener "load""unload" 事件,但只有最后加载的 window.onloadwindow.onunload 事件将被执行。