Reputation: 73
I have in my onInit in the controller following code:
$("input").on("keydown", (
function(evt) {
if (evt.keyCode == 17 && (evt.ctrlKey)) {
evt.preventDefault();
that.onMoveStorageBin();
}
So idea is, when I press F11 button, onMoveStorageBin function would be executed. But it does not go into the onInit when I press any button. Where is the correct place to put this handling of the keydown? Thanks, Tim
Upvotes: 0
Views: 2469
Reputation: 5206
You should execute your code snippet on the onAfterRendering lifecycle hook. This is because in the onInit, the jQuery call will not be able to find any input (as the elements corresponding to your view were not yet added to the DOM).
Based on the description and code, I understand that you need to check if the F11 + CTRL was pressed (hence the check is evt.keyCode == 122 && evt.ctrlKey
); if you want a sinple F11, the you only need to check evt.keyCode == 122
.
You can find a working fiddle here: https://jsfiddle.net/8kcs8xch/4/
onAfterRendering: function() {
jQuery("input").on("keydown",
function(evt) {
if (evt.keyCode == 122 && evt.ctrlKey) {
evt.preventDefault();
sap.m.MessageToast.show('Alert');
}
});
}
This approach has the following limitations:
A considerably better solution would be to create a custom control which has this event. You can find an example here: https://jsfiddle.net/8kcs8xch/3/
Basically you need to listen to the keydown event by declaring a DOM handler in your new control. You can then define a custom UI5 event (I simply called it alert
) based on this DOM event:
var CustomInput = sap.m.Input.extend("CustomInput", {
metadata: {
events: {alert: {}}
},
onkeydown: function(evt) {
if (evt.keyCode == 122 && evt.ctrlKey) {
// only prevent the default of the DOM event if the
// UI5 event's preventDefault is called as well.
if (!this.fireEvent("alert", {}, true)) {
evt.preventDefault();
}
}
},
renderer: {}
});
Upvotes: 1