首页 > 解决方案 > SAPUI5:视图/页面上的按键

问题描述

在我的 sapui5 应用程序中,我的 Home 控制器中有以下代码

onAfterRendering: function() {
var s = this;

document.addEventListener("keypress", function onPress(event) {
     if ( event.keyCode === 50) {
        alert("Test");
  }
});

因此,当我按下键时,由于元素“文档”,消息将显示在主视图和其他视图中

但我希望在每个视图/控制器中都有一个其他功能或消息到相同的键码。

那么如何附加到特定视图?我不想将它附加到控件上。

标签: sapui5keycode

解决方案


每次访问视图时,您都必须删除并添加事件监听器。

视图1:

onInit: function(){
    this.getRouter().getRoute("myView1").attachMatched(this._onRouteMatched, this); //Call _onRouteMatched on every visit from myView1
},

_onRouteMatched: function (oEvent) {
    document.removeEventListener("keypress"); //Remove the event listener
    document.addEventListener("keypress", function onPress(event) { //Add the event listener again with another message
        if ( event.keyCode === 50) {
            alert("Test View 1");
    }
}

视图2:

onInit: function(){
    this.getRouter().getRoute("myView2").attachMatched(this._onRouteMatched, this); 
},

_onRouteMatched: function (oEvent) {
    document.removeEventListener("keypress");
    document.addEventListener("keypress", function onPress(event) {
        if ( event.keyCode === 50) {
            alert("Test View 2");
    }
}

推荐阅读