How does the lifecycle of UI5 Controls work?

André Shevantes picture André Shevantes · Feb 24, 2015 · Viewed 32.7k times · Source

Can someone give a more detailed explanation about the lifecycle of the default events of a UI5 Control? I know there is this page on the documentation that gives an overview of a Control lifecycle, however, I think it is very brief and wanted something more detailed. Can someone list the order of the events of a Control and explain what every event does?

Answer

cschuff picture cschuff · Feb 24, 2015

You are absolutely right. The details of a Control lifecycle and implementation details are very well hidden in the docs. I'll try to sum up my so far understanding for you.

The lifecycle of a Control is mainly determined by:

  • init : Your little Control is born! Function is called by the framework during constructor execution. Do your initialization stuff here.
  • onBeforeRendering : Called by the framework before the rendering of the control is started. Triggers before every (re)rendering.
  • onAfterRendering : Called by the framework after the rendering of the control has completed. Triggers after every (re)rendering.
  • exit : RIP little Control! Cleans up the element instance before destruction. Called by the framework. Do your clean up here. Btw: If you need to explicitly destruct a Control/Element you should call destroy and not directly exit.

Here is a sample implementation with some sample usages for the different hooks:

sap.ui.core.Control.extend("a.sample.Control", {
  init : function() {
    // instantiate a sub-control
    this._btn = new sap.m.Button(); 
  },

  onBeforeRendering : function() {
    // deregister a listener via jQuery
    this.$("subelement").off("click", this.subElementClick);
  },

  onAfterRendering : function() {
    // register a listener via jQuery on a sub-element
    this.$("subelement").on("click", this.subElementClick);
  },

  subElementClick : function() {
    // do stuff
  },

  exit : function() {
    // clean up sub-controls and local references
    this._btn.destroy();
    delete this._btn;
  }

});

Why shouldn't I do my init stuff in my constructor?

There is a basic UI5 constructor in ManagedObject. It "prepares" your UI5 object for you and calls your init function afterwards. That means in your init all settings will already be applied for you and you can access properties and aggregations as usual.

Why shouldn't I call rerender?

The SAPUI5 rendering is intelligent in a sense that it groups and optimizes queued rerenderings. Therefore you should never call rerender directly but instead use invalidate to mark a control for rerendering.

HF

Chris