class sap.ui.core.mvc.Controller

Visiblity: public
UX Guidelines:
Implements:
Available since: N/A
Module: sap/ui/core/mvc/Controller
Application Component: CA-UI5-COR

A generic controller implementation for the UI5 Model-View-Controller concept.

Can be used as a base class for typed controllers.

Typed Controller Scenario:


Constructor

Instantiates a (MVC-style) controller.

new sap.ui.core.mvc.Controller(sName)
Param Type Default Value Description
sName string object[]

The name of the controller to instantiate. If a controller is defined as real sub-class, the "arguments" of the sub-class constructor should be given instead.


Methods Overview

Method Description
byId

Returns an Element of the connected view with the given local ID.

Views automatically prepend their own ID as a prefix to created Elements to make the IDs unique even in the case of multiple view instances. This method helps to find an element by its local ID only.

If no view is connected or if the view doesn't contain an element with the given local ID, undefined is returned.

sap.ui.core.mvc.Controller.create

Creates an instance of controller class.

createId

Converts a view local ID to a globally unique one by prepending the view ID.

If no view is connected, undefined is returned.

sap.ui.core.mvc.Controller.extend

Creates a new subclass of class sap.ui.core.mvc.Controller with name sClassName and enriches it with the information contained in oClassInfo.

oClassInfo might contain the same kind of information as described in sap.ui.base.EventProvider.extend.

sap.ui.core.mvc.Controller.getMetadata

Returns a metadata object for class sap.ui.core.mvc.Controller.

getOwnerComponent

Gets the component of the controller's view

If there is no Component connected to the view or the view is not connected to the controller, undefined is returned.

getView

Returns the view associated with this controller or undefined.

loadFragment

Loads a Fragment by sap.ui.core.Fragment.load.

The fragment content will be added to the dependents aggregation of the view by default. This behavior can be suppressed by setting mOptions.addToDependents to false.

The controller is passed to the Fragment by default, so the (event handler) methods referenced in the Fragment will be called on this Controller.

If the controller has an owner component, it is passed to the fragment content. By default the fragment content will be prefixed with the view ID to avoid duplicate ID issues. The prefixing can be switched off with the autoPrefixId option.

When autoPrefixId is enabled, the fragment content can be accessed by calling sap.ui.core.mvc.Controller.byId.

Destroy behavior: Different scenarios concerning the destruction of the fragment's content exist, of which some must be addressed by the caller, while others are handled automatically.

  • The controller instance is destroyed before the fragment content creation has finished: In this case, the controller instance takes care of asynchronously destroying the fragment content
  • The fragment content is aggregated within a control (e.g. dependents aggregation by default): In this case, the content will be destroyed during the regular destroy lifecycle.
  • The fragment content is not aggregated within a control: In this case, it must be destroyed manually in the exit hook of the controller.

onAfterRendering

This method is called every time the View is rendered, after the HTML is placed in the DOM-Tree. It can be used to apply additional changes to the DOM after the Renderer has finished. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

References:

  • sap.ui.core.Control.prototype.onAfterRendering

onBeforeRendering

This method is called every time the View is rendered, before the Renderer is called and the HTML is placed in the DOM-Tree. It can be used to perform clean-up-tasks before re-rendering. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

References:

  • sap.ui.core.Control.prototype.onBeforeRendering

onExit

This method is called upon desctuction of the View. The controller should perform its internal destruction in this hook. It is only called once per View instance, unlike the onBeforeRendering and onAfterRendering hooks. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

onInit

This method is called upon initialization of the View. The controller can perform its internal setup in this hook. It is only called once per View instance, unlike the onBeforeRendering and onAfterRendering hooks. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

Note: In component-based apps this.getOwnerComponent().getModel() should be used inside onInit() to get a model assigned to the component instead of using this.getView().getModel(). The latter call might return undefined because the view might not have been attached to a parent yet (i.e. the component), and thus the view can't inherit a model from that parent. You could also attach to the modelContextChange event. The event is fired when either the context or the model changes for the control.

sap.ui.core.mvc.Controller.registerExtensionProvider

Registers a callback module, which provides code enhancements for the lifecycle and event handler functions of a specific controller. The code enhancements are returned either in sync or async mode.

The extension provider module provides the getControllerExtensions function which returns either directly an array of objects or a Promise that returns an array of objects when it resolves. These objects are object literals defining the methods and properties of the controller in a similar way as for Controller subclasses.

Example for a callback module definition (sync):

sap.ui.define("my/custom/sync/ExtensionProvider", ['jquery.sap.global'], function(jQuery) {
  var ExtensionProvider = function() {};
  ExtensionProvider.prototype.getControllerExtensions = function(sControllerName, sComponentId, bAsync) {
    if (!bAsync && sControllerName == "my.own.Controller") {
      // IMPORTANT: only return extensions for a specific controller
      return [{
        onInit: function() {
          // Do something here...
        },
        onAfterRendering: function() {
          // Do something here...
        },
        onButtonClick: function(oEvent) {
          // Handle the button click event
        }
      }
    }];
  };
  return ExtensionProvider;
}, true);

Example for a callback module definition (async):

sap.ui.define("my/custom/async/ExtensionProvider", ['jquery.sap.global'], function(jQuery) {
  var ExtensionProvider = function() {};
  ExtensionProvider.prototype.getControllerExtensions = function(sControllerName, sComponentId, bAsync) {
    if (bAsync && sControllerName == "my.own.Controller") {
      // IMPORTANT:
      // only return a Promise for a specific controller since it
      // requires the View/Controller and its parents to run in async
      // mode!
      return new Promise(function(fnResolve, fnReject) {
        fnResolve([{
          onInit: function() {
            // Do something here...
          },
          onAfterRendering: function() {
            // Do something here...
          },
          onButtonClick: function(oEvent) {
            // Handle the button click event
          }
        }]);
      }
    };
  };
  return ExtensionProvider;
}, true);

The lifecycle functions onInit, onExit, onBeforeRendering and onAfterRendering are added before or after the lifecycle functions of the original controller. The event handler functions, such as onButtonClick, are replacing the original controller's function.

When using an async extension provider you need to ensure that the view is loaded in async mode.

In both cases, return undefined if no controller extension shall be applied.

byId

Returns an Element of the connected view with the given local ID.

Views automatically prepend their own ID as a prefix to created Elements to make the IDs unique even in the case of multiple view instances. This method helps to find an element by its local ID only.

If no view is connected or if the view doesn't contain an element with the given local ID, undefined is returned.

Param Type DefaultValue Description
sId string

View-local ID

sap.ui.core.mvc.Controller.create

Creates an instance of controller class.

Param Type DefaultValue Description
mOptions object

A map containing the controller configuration options.

name string

The controller name that corresponds to a JS module that can be loaded via the module system (mOptions.name + suffix ".controller.js")

createId

Converts a view local ID to a globally unique one by prepending the view ID.

If no view is connected, undefined is returned.

Param Type DefaultValue Description
sId string

View-local ID

sap.ui.core.mvc.Controller.extend

Creates a new subclass of class sap.ui.core.mvc.Controller with name sClassName and enriches it with the information contained in oClassInfo.

oClassInfo might contain the same kind of information as described in sap.ui.base.EventProvider.extend.

Param Type DefaultValue Description
sClassName string

Name of the class being created

oClassInfo object

Object literal with information about the class

FNMetaImpl function

Constructor function for the metadata object; if not given, it defaults to the metadata implementation used by this class

sap.ui.core.mvc.Controller.getMetadata

Returns a metadata object for class sap.ui.core.mvc.Controller.

getOwnerComponent

Gets the component of the controller's view

If there is no Component connected to the view or the view is not connected to the controller, undefined is returned.

getView

Returns the view associated with this controller or undefined.

loadFragment

Loads a Fragment by sap.ui.core.Fragment.load.

The fragment content will be added to the dependents aggregation of the view by default. This behavior can be suppressed by setting mOptions.addToDependents to false.

The controller is passed to the Fragment by default, so the (event handler) methods referenced in the Fragment will be called on this Controller.

If the controller has an owner component, it is passed to the fragment content. By default the fragment content will be prefixed with the view ID to avoid duplicate ID issues. The prefixing can be switched off with the autoPrefixId option.

When autoPrefixId is enabled, the fragment content can be accessed by calling sap.ui.core.mvc.Controller.byId.

Destroy behavior: Different scenarios concerning the destruction of the fragment's content exist, of which some must be addressed by the caller, while others are handled automatically.

Param Type DefaultValue Description
mOptions object

Options regarding fragment loading

name string

The Fragment name, which must correspond to a Fragment which can be loaded via the module system (fragmentName + suffix ".fragment.[typeextension]") and which contains the Fragment definition.

addToDependents object true

Whether the fragment content should be added to the dependents aggregation of the view

autoPrefixId object true

Whether the IDs of the fragment content will be prefixed by the view ID

id string

the ID of the Fragment

type string XML

the Fragment type, e.g. "XML", "JS", or "HTML" (see above). Default is "XML"

onAfterRendering

This method is called every time the View is rendered, after the HTML is placed in the DOM-Tree. It can be used to apply additional changes to the DOM after the Renderer has finished. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

References:

onBeforeRendering

This method is called every time the View is rendered, before the Renderer is called and the HTML is placed in the DOM-Tree. It can be used to perform clean-up-tasks before re-rendering. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

References:

onExit

This method is called upon desctuction of the View. The controller should perform its internal destruction in this hook. It is only called once per View instance, unlike the onBeforeRendering and onAfterRendering hooks. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

onInit

This method is called upon initialization of the View. The controller can perform its internal setup in this hook. It is only called once per View instance, unlike the onBeforeRendering and onAfterRendering hooks. (Even though this method is declared as "abstract", it does not need to be defined in controllers, if the method does not exist, it will simply not be called.)

Note: In component-based apps this.getOwnerComponent().getModel() should be used inside onInit() to get a model assigned to the component instead of using this.getView().getModel(). The latter call might return undefined because the view might not have been attached to a parent yet (i.e. the component), and thus the view can't inherit a model from that parent. You could also attach to the modelContextChange event. The event is fired when either the context or the model changes for the control.

sap.ui.core.mvc.Controller.registerExtensionProvider

Registers a callback module, which provides code enhancements for the lifecycle and event handler functions of a specific controller. The code enhancements are returned either in sync or async mode.

The extension provider module provides the getControllerExtensions function which returns either directly an array of objects or a Promise that returns an array of objects when it resolves. These objects are object literals defining the methods and properties of the controller in a similar way as for Controller subclasses.

Example for a callback module definition (sync):

sap.ui.define("my/custom/sync/ExtensionProvider", ['jquery.sap.global'], function(jQuery) {
  var ExtensionProvider = function() {};
  ExtensionProvider.prototype.getControllerExtensions = function(sControllerName, sComponentId, bAsync) {
    if (!bAsync && sControllerName == "my.own.Controller") {
      // IMPORTANT: only return extensions for a specific controller
      return [{
        onInit: function() {
          // Do something here...
        },
        onAfterRendering: function() {
          // Do something here...
        },
        onButtonClick: function(oEvent) {
          // Handle the button click event
        }
      }
    }];
  };
  return ExtensionProvider;
}, true);

Example for a callback module definition (async):

sap.ui.define("my/custom/async/ExtensionProvider", ['jquery.sap.global'], function(jQuery) {
  var ExtensionProvider = function() {};
  ExtensionProvider.prototype.getControllerExtensions = function(sControllerName, sComponentId, bAsync) {
    if (bAsync && sControllerName == "my.own.Controller") {
      // IMPORTANT:
      // only return a Promise for a specific controller since it
      // requires the View/Controller and its parents to run in async
      // mode!
      return new Promise(function(fnResolve, fnReject) {
        fnResolve([{
          onInit: function() {
            // Do something here...
          },
          onAfterRendering: function() {
            // Do something here...
          },
          onButtonClick: function(oEvent) {
            // Handle the button click event
          }
        }]);
      }
    };
  };
  return ExtensionProvider;
}, true);

The lifecycle functions onInit, onExit, onBeforeRendering and onAfterRendering are added before or after the lifecycle functions of the original controller. The event handler functions, such as onButtonClick, are replacing the original controller's function.

When using an async extension provider you need to ensure that the view is loaded in async mode.

In both cases, return undefined if no controller extension shall be applied.

Param Type DefaultValue Description
sExtensionProvider string

the module name of the extension provider

See sap.ui.core.mvc.Controller for an overview of the available functions for controllers.