Improve this

Page Lifecycle

Due to the asynchronous nature of JavaScript and animations, Onsen UI provides ons-page life cycle to perform actions at the right time. Loading data, updating the view, saving data before destroying… all of these and more actions are examples of what can be done thanks to page’s life cycle.

Events

<ons-page> provides a set of DOM events that will be fired in unique and set times of its life cycle. Use these events to alter the behavior on each page.

Page lifecycle events will be propagated to the page’s descendants so they are correspondingly shown, hidden, or destroyed. For example, destroying <ons-navigator> will throw hide event only for the displayed page (navigator’s top page) and destroy event for every page in navigator’s page stack.

Since lifecycle events are normal DOM events and bubble up, you can add a listener to the document or any parent element of the page. The event object contains a reference to the page itself (event.target).

<ons-page id="page1">This is a blank page</ons-page>

<script>
document.addEventListener('init', function(event) {
  if (event.target.matches('#page1')) {
    ons.notification.alert('Page 1 is initiated.');
    // Set up content...
  }
}, false);
</script>

Hooks

As the support for native <template> elements had been added since v2.4.0, lifecycle hooks are also available. Hooks are run at the same time as the corresponding events:

<template id="page1.html">
  <ons-page>
    <ons-toolbar>
      <div class="center"></div>
    </ons-toolbar>
    <!-- More content here -->

    <script>
      ons.getScriptPage().onInit = function() {
        // Set up page's content or anything else
        this.querySelector('ons-toolbar .center').innerHTML = 'Title';

        this.onShow = function() { ... };
        this.onHide = function() { ... };
        this.onDestroy = function() { ... };
      };
    </script>
  </ons-page>
</template>

Keep in mind that there can only be 1 root node per template (an ons-page). Optionally, <template> elements allow synchronous <script></script> tags inside that run when the element is created and attached to the DOM.

This script is evaluated in the global scope and anything that you write here might affect any other part of your app. For example, variables declared in this script will pollute the global scope unless it is wrapped inside a closure.

In the previous example, ons.getScriptPage() method simply gets the parent ons-page that has just been attached. Notice that this method only works in this situation (inside script tags and direct child of ons-page) and was included in `onsenui@2.5.2`. Another alternative is getting the page element by class or id.

It is up to the developer choosing between events or hooks. Events allow separating the view from the logic while hooks provide a more compact approach.