Skip to content

Instantly share code, notes, and snippets.

@cschuff
Created November 22, 2017 09:53
Show Gist options
  • Save cschuff/775b1d4e6d09c37f0b2edb76d40be474 to your computer and use it in GitHub Desktop.
Save cschuff/775b1d4e6d09c37f0b2edb76d40be474 to your computer and use it in GitHub Desktop.
Autofocus a SAPUI5 control everytime a View is shown (if Router is used)
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("ui5experts.controller.Autofocus", {
onInit: function() {
this.getRouter().attachRoutePatternMatched(this.onRoutePatternMatched, this);
},
onExit: function() {
this.getRouter().detachRoutePatternMatched(this.onRoutePatternMatched, this);
},
onRoutePatternMatched: function(oEv) {
var oCtrl = this.getView().byId("AutofocusControl");
if (oCtrl.getDomRef()) {
// control is rendered yet, apply focus immediately
oCtrl.focus();
} else {
// control is NOT rendered yet, apply focus after rendering
var oDel = {
onAfterRendering: function() {
// does not work immediately in onAfterRendering, therefore using timeout
jQuery.sap.delayedCall(0, function() {
this.focus();
// remove delegate again since we only want to do this once per routePatternMatched
this.removeEventDelegate(oDel);
}.bind(this));
}.bind(oCtrl)
}
oCtrl.addEventDelegate(oDel);
}
}
})
});
Copy link

ghost commented Jul 5, 2018

There seems to be a bug.

According to the documentation, the scope is missing:
jQuery.sap.delayedCall(0, this, function() {

See: https://sapui5.hana.ondemand.com/#/api/jQuery.sap/methods/jQuery.sap.delayedCall

I tried your code but used a control from within a fragment instead. Did not work until I added the scope explicitly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment