Search code examples
model-view-controllercontrollersapui5

SAPUI5 Create Controller Without View


I am developing an application by using SAPUI5, Web IDE. Is it possible to create a controller without a view? Because I need a custom controller to process the logic of application before submit it to the server.

I try to create a controller without with view. But it return me with error.

The following is my sample code.

/*global location*/
sap.ui.define([
    "product/controller/BaseController",
    "sap/ui/model/json/JSONModel",
    "sap/ui/core/routing/History",
    "product/model/formatter"
], function(BaseController, JSONModel, History, formatter) {

        onInit: function() {
            sap.ui.getCore().getEventBus().subscribe(
                "SomeChannel",
                "SomeEvent",
                this.someFunctionOfTheFirstController,
                this
            );
        }

    processLogic: function (sChannelId, sEventId, sData) {
        console.log(
            "Function of the first controller " + sData
        );
    }
});

Any solution how can I fix it and to create a controller and method without a view.


Solution

  • I guess you have to return the controller object itself. You are importing the BaseController, so your controller could look like this:

    sap.ui.define([
        "product/controller/BaseController",
        "sap/ui/model/json/JSONModel",
        "sap/ui/core/routing/History",
        "product/model/formatter"
    ], function(BaseController, JSONModel, History, formatter) {
    
        return BaseController.extend("product.controller.MyController", {
            onInit: function() {
                sap.ui.getCore().getEventBus().subscribe(
                    "SomeChannel",
                    "SomeEvent",
                    this.someFunctionOfTheFirstController,
                    this
                );
            },
    
            processLogic: function (sChannelId, sEventId, sData) {
                console.log("Function of the first controller " + sData);
            }
       });
    });
    

    Afterwards you can load your controller by calling:

    const myController = sap.ui.controller("product.controller.MyController");