Created
November 22, 2017 09:53
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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