Search code examples
dependency-injectionsapui5

"'this.byId' is not a Function" error in console


I have a script file that I would like to load into a Main.controller.js

myScript.js

sap.ui.define([], function () {

    return {
        /////
        testFunc : function(){

                var test = this.byId("someId");
                console.log(test);
    };
});

The myScript.js file is successfully read in the main controller when I load it in as a dependency (see below), but I get an error in the myScript.js :

"'this.byId' is Not a Function" (console.log)

Inside the main controller, "this.byId()" works because the 'this' keyword points to the xml view associated with the main controller (main.view.xml). How can I have a dependency like 'myScript.js' point to the same xml view as the controller that loads it?

main controller

sap.ui.define([
        'jquery.sap.global',
        'sap/ui/core/mvc/Controller',
        'sap/ui/model/json/JSONModel',
        'sap/ui/model/Filter',
        'sap/ui/model/FilterOperator',
        'pricingTool/controller/myScript'
    ],

    function (jQuery, Controller, JSONModel, Filter, FilterOperator, myScript) {
        "use strict";


        var mainController = Controller.extend("pricingTool.controller.Main", {
       
        myScript.testFunc();

       ...

     });

    return mainController;
});

main.view.xml

<mvc:View
    controllerName="pricingTool.controller.Main"
    xmlns:l="sap.ui.layout"
    xmlns:core="sap.ui.core"
    xmlns:f="sap.ui.layout.form"
    xmlns:mvc="sap.ui.core.mvc"
    xmlns="sap.m">
    ...
</mvc:View>

Solution

  • You need to change the context passed to the script function. You can do this with following code:

     myScript.testFunc.apply(this);
    

    Let me know if this resolved your issue.