cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

SAPUI5 : Controller.js accessing global variable in different functions

Badhusha
Participant
0 Likes
2,335

Hi everyone,

In my controller.js I tried to create on global variable . I will set that in _onRouteFound() function . But when I try to consume in onAfterRendering() function, it is showing undefined.

How should I declare the global variable ?

sap.ui.define([
	"sap/ui/core/mvc/Controller"
], function (Controller) {
	"use strict";
	return Controller.extend("novigoapplications.NovigoApp.controller.FODetail", {
		onInit: function () {
			this.getView().byId("map_canvas").addStyleClass("googleMap");
			var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.getRoute("Route_FODetail").attachMatched(this._onRouteFound, this);
		},
		_onRouteFound: function (oEvt) {
			var oArgument = oEvt.getParameter("arguments");
			var oView = this.getView();
			oView.bindElement({
				path: "/FreightOrderSet('" + oArgument.SelectedItem + "')",
				events: {
					dataReceived: function (response) {
						this.name = "Allen";  /** Assigning the value**/
						console.log(response.mParameters.data);
					}
				}
			});
		},
		onAfterRendering: function () {
                  console.log(this.name);   /** This is still printing undefined **/
		},
	});
});

Accepted Solutions (1)

Accepted Solutions (1)

mariusobert
Developer Advocate
Developer Advocate

If you want to define a global variable in JavaScript, you need to do that with

window.name = "Allen"

But please be careful, using global variables is usually an anti-pattern and can lead to bad coding practices. It would be better to pass this value via a function call or maybe store it in a controller property.

PS: Here's an article about what "this" is in JavaScript.

Answers (0)