How to use module in SAPUI5

According to my understanding, module and controller is different.

1. Controller

Controller is used in view, handling the event triggered in view. The most explicate feature is to extend “sap/ui/core/mvc/Controller”.

Like this:

sap.ui.define([
   "sap/ui/core/mvc/Controller"
], function (Controller) {
   "use strict";
   return Controller.extend("sap.ui.demo.walkthrough.controller.App", {
      onShowHello : function () {
         // show a native JavaScript alert
         alert("Hello World");
      }
   });
});

Step 5: Controllers – Documentation – Demo Kit – SAPUI5 SDK (ondemand.com)

 

2. Module

Firstly, module is a normal principle for javascript. You can see this toturial: https://sapui5.hana.ondemand.com/#/topic/50579ddf2c934ce789e056cfffe9efa9

2.1 Usage

  • Clean your code by module.
  • Use module in your fragment. For fragment, you can assign a controller to the fragment when it’s loaded. Or you can use import module in fragment and use it like the below code:
<core:FragmentDefinition
	xmlns="sap.m"
	xmlns:core="sap.ui.core">
	<Dialog core:require="{ handler: 'sap/ui/demo/walkthrough/module/HelloDialog'}"
		id="helloDialog"
		title="Hello {/recipient/name}">
		<Button text="Button in Dialog"
				press="handler.onRaiseMessage"></Button>
	</Dialog>
</core:FragmentDefinition>

In some application generated by Fiori Element, it will be convenient to use the module in fragment. Since the controller and view are invisible.

2.2 Example

  • Use sap.ui.define to define module.
  • Import library.
  • Define private method.
  • Define public method(In the return statement).
sap.ui.define([
    "sap/m/MessageToast"
], function (MessageToast) {
    'use strict';

    var privateMethod_1 = function () {
        MessageToast.show("Active private method");
    };

    return {
        onRaiseMessage: function (oEvent) {
            privateMethod_1();
        }
    }
});

There are some points needs your attention:

  • The public method cannot call another public method, it only can call private method. I am not clear the reason, if you know that, feel free to add comment.
  • If you debug the statement “MessageToast.show(…)”, you will find that this refers to the view controller not the module. You can use it to operate model or do other things.

Original Article:
https://blogs.sap.com/2023/05/31/how-to-use-module-in-sapui5/

ASK SAP EXPERTS ONLINE
Related blogs

LEAVE A REPLY

Please enter your comment!
Please enter your name here