Search code examples
sapui5

How to call utility functions in SAPUI5 controller


I want to create a custom utility file (JavaScript file) i.e. /webapp/util/MyUtil.js

Assuming this is the content of the MyUtil:

function myFunc(input) {
    // some code
}

And there exist a view and controller i.e. View1.xml and View1.js. How can I call myFunct(input) from View1.js?


Solution

  • The recommended way is to create a module (similar to class), which can handle your dependencies in the future:

    sap.ui.define([], function() {
       "use strict";
    
       return {
          myFunc: function(input) {
             // some code
          }
       };
    });
    

    Later, in your controller include this file in the dependencies list and access it through this object:

    sap.ui.define([
       "sap/ui/core/mvc/Controller",
       "./MyUtils"
    ], function(Controller, MyUtils) {
       "use strict";
    
       return Controller.extend("your.controller.ControllerName", {
          myFunc2: function(input) {
             MyUtils.myFunc(input);
          }
       });
    });
    

    Make sure that you specify the correct path. If it's controller's folder, you can use the example, otherwise point to the proper folder.