Deno支持与浏览器兼容的生命周期事件:load和unload。您可以使用这些事件在程序中提供设置和清除代码。
load事件的侦听器可以是异步的,将被等待。unload事件的侦听器必须是同步的。这两个事件都无法取消。
例子:
main.ts
import "./imported.ts";
const handler = (e: Event): void => {
console.log(`got ${e.type} event in event handler (main)`);
};
window.addEventListener("load", handler);
window.addEventListener("unload", handler);
window.onload = (e: Event): void => {
console.log(`got ${e.type} event in onload function (main)`);
};
window.onunload = (e: Event): void => {
console.log(`got ${e.type} event in onunload function (main)`);
};
console.log("log from main script");
导入的
const handler = (e: Event): void => {
console.log(`got ${e.type} event in event handler (imported)`);
};
window.addEventListener("load", handler);
window.addEventListener("unload", handler);
window.onload = (e: Event): void => {
console.log(`got ${e.type} event in onload function (imported)`);
};
window.onunload = (e: Event): void => {
console.log(`got ${e.type} event in onunload function (imported)`);
};
console.log("log from imported script");
请注意,您可以同时使用window.addEventListener和 window.onload/window.onunload来定义事件的处理程序。它们之间有一个主要区别,让我们运行示例:
$ 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)
使用添加的所有听众window.addEventListener都跑,但 window.onload和window.onunload定义main.ts中定义凌驾于处理器imported.ts。
换句话说,您可以注册多个window.addEventListener "load"或 "unload"事件,但是将仅执行上次加载的 事件window.onload或window.onunload事件处理程序。因此,最好addEventListener在可能的情况下使用。
网友评论