2020-05-06 18:21:13 -04:00
|
|
|
## Program lifecycle
|
|
|
|
|
|
|
|
Deno supports browser compatible lifecycle events: `load` and `unload`. You can
|
|
|
|
use these events to provide setup and cleanup code in your program.
|
|
|
|
|
2020-05-18 15:53:25 -04:00
|
|
|
Listeners for `load` events can be asynchronous and will be awaited. Listeners
|
|
|
|
for `unload` events need to be synchronous. Both events cannot be cancelled.
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
2020-05-09 21:09:42 -04:00
|
|
|
```ts
|
2020-05-06 18:21:13 -04:00
|
|
|
// 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)`);
|
|
|
|
};
|
|
|
|
|
2020-05-15 10:27:38 -04:00
|
|
|
console.log("log from main script");
|
|
|
|
|
2020-05-06 18:21:13 -04:00
|
|
|
// imported.ts
|
|
|
|
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");
|
|
|
|
```
|
|
|
|
|
|
|
|
Note that you can use both `window.addEventListener` and
|
|
|
|
`window.onload`/`window.onunload` to define handlers for events. There is a
|
2020-05-18 15:53:25 -04:00
|
|
|
major difference between them, let's run the example:
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```shell
|
|
|
|
$ deno run main.ts
|
|
|
|
log from imported script
|
|
|
|
log from main script
|
|
|
|
got load event in onload function (main)
|
|
|
|
got load event in event handler (imported)
|
|
|
|
got load event in event handler (main)
|
|
|
|
got unload event in onunload function (main)
|
|
|
|
got unload event in event handler (imported)
|
|
|
|
got unload event in event handler (main)
|
|
|
|
```
|
|
|
|
|
|
|
|
All listeners added using `window.addEventListener` were run, but
|
2020-05-17 13:24:39 -04:00
|
|
|
`window.onload` and `window.onunload` defined in `main.ts` overrode handlers
|
2020-05-06 18:21:13 -04:00
|
|
|
defined in `imported.ts`.
|