diff options
author | Bartek IwaĆczuk <biwanczuk@gmail.com> | 2019-10-02 17:32:51 +0200 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2019-10-02 11:32:51 -0400 |
commit | c920c5f62aba7eee0f6fa70f68f701e204ac1a9c (patch) | |
tree | 3ab590972146e11d75f1ddd296ab1a6aead58906 /website | |
parent | d32f39f2ec271c7517bbd5113827dc43a7e40641 (diff) |
feat: window.onunload (#3023)
Diffstat (limited to 'website')
-rw-r--r-- | website/manual.md | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/website/manual.md b/website/manual.md index 7a659460c..dabb08e41 100644 --- a/website/manual.md +++ b/website/manual.md @@ -928,6 +928,76 @@ window.onload = async function() { $ deno run --importmap=import_map.json hello_server.ts ``` +## Program lifecycle + +Deno supports browser compatible lifecycle events: `load` and `unload`. You can +use these event to provide setup and cleanup code in your program. + +`load` event listener supports asynchronous functions and will await these +functions. `unload` event listener supports only synchronous code. Both events +are not cancellable. + +Example: + +```typescript +// 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)`); +}; + +// 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 +major difference between them, let's run example: + +```shell +$ deno 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 +`window.onload` and `window.onunload` defined in `main.ts` overridden handlers +defined in `imported.ts`. + ## Internal details ### Deno and Linux analogy |