diff options
author | Luca Casonato <lucacasonato@yahoo.com> | 2020-05-07 00:21:13 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-06 18:21:13 -0400 |
commit | 34ec3b225425cecdccf754fbc87f4a8f3728890d (patch) | |
tree | 35db52bf25ccf64425692116197df61a69ea8838 /docs/runtime/program_lifecycle.md | |
parent | 846c049c9b3ab36d0893292a204c4d0a18de4c8e (diff) |
Multi page manual (#5110)
Diffstat (limited to 'docs/runtime/program_lifecycle.md')
-rw-r--r-- | docs/runtime/program_lifecycle.md | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/docs/runtime/program_lifecycle.md b/docs/runtime/program_lifecycle.md new file mode 100644 index 000000000..dda8a06f9 --- /dev/null +++ b/docs/runtime/program_lifecycle.md @@ -0,0 +1,68 @@ +## 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. + +Listener for `load` events can be asynchronous and will be awaited. Listener for +`unload` events need to be synchronous. Both events cannot be cancelled. + +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 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 +`window.onload` and `window.onunload` defined in `main.ts` overridden handlers +defined in `imported.ts`. |