Search code examples
sapui5

How to split a controller file in SAPUI5?


I'm wondering how to split a controller.js file? We've a folder "abcd, in this folder we've "controller", "view", "manifest.json" as well as "Component.js" and in that "controller" folder, we've only one file called "File.controller.js". This is a very big file, that's why I want to split/extend this file. Could anyone please share your knowledge here? Thanks a lot in advance!


Solution

  • The mechanism for this is similar to extracting new classes in Object-oriented programming languages. Once you find cohesive pieces of code that can be extracted as a separate component, you can choose to create a new file e.g. "ExtractedComponent.js" that has the following structure: e.g.

    sap.ui.define([], function() {
     "use strict";
    
     // implement the extracted functionality here
     ...
    }
    

    and then you can use this extracted component as a dependency in your controller. Just add it to the File.controller.js correctly, e.g.:

    sap.ui.define([
     ...,
    /path/to/extracted/component/ExtractedComponent.js
    ...],
    function(..., ExtractedComponent, ...) {
    ...
    });
    

    and then use it wherever necessary. To name a few examples, we extracted such reusable pieces of code that manage filters, date formatting, OData clients, etc.