从控件中检索 id 以在导航中使用

Retrieving the id from a control to use in navigation

我有一个带有图块的视图,每个图块都有一个 id="foo" 属性,以及一个指向控制器中功能的按键 属性。

问题是我可以获得图块的 ID,但它会自动附加到视图名称,__xmlview1--foo1。如果已经创建了其他视图,这可能会改变;不能保证它永远是 xmlview1,它可以是 xmlview2 或任何更高的数字。

如何检索出现在图块 ID 属性 中的纯 ID?这个 switch 语句是执行导航的最佳方式,还是有更多 robust/elegant 解决方案?

onPress: function(oEvent){
  switch(oEvent.getSource().sId) {
    case "__xmlview1--foo1":
      this.oRouter.navTo("myview1");
      break;
    case "__xmlview1--foo2":
      this.oRouter.navTo("myview2");
      break;
    case "__xmlview1--foo3":
      this.oRouter.navTo("myview3");
      break;
    case "__xmlview1--foo4":
      this.oRouter.navTo("myview4");
      break;
    case "__xmlview1--foo5":
      this.oRouter.navTo("myview5");
      break;
    default:
      console.log("No match found.");
}

您可以将格式更改为 _xmlviewX--myviewX,然后只需从 -- 中提取子字符串并导航至 link。

最简单的解决方案是放弃转换并改用 indexOf/if..else

var id = oEvent.getSource().sId;

if (id.indexOf('foo1') > -1) {
    this.oRouter.navTo("myview1");
} else if (id.indexOf('foo2') > -1) {
    this.oRouter.navTo("myview2");
} else if (id.indexOf('foo3') > -1) {
    this.oRouter.navTo("myview3");
} else if (id.indexOf('foo4') > -1) {
    this.oRouter.navTo("myview4");
} else if (id.indexOf('foo5') > -1) {
    this.oRouter.navTo("myview5");
} else {
    console.log("No match found.");
}

但是,如果您必须使用switch,您可以使用test

对ID进行正则表达式
onPress: function(oEvent){

    var id = oEvent.getSource().sId;

    switch(true) {
        case /foo1/.test(id):
          this.oRouter.navTo("myview1");
          break;
        case /foo2/.test(id):
          this.oRouter.navTo("myview2");
          break;
        case /foo3/.test(id):
          this.oRouter.navTo("myview3");
          break;
        case /foo4/.test(id):
          this.oRouter.navTo("myview4");
          break;
        case /foo5/.test(id):
          this.oRouter.navTo("myview5");
          break;
        default:
          console.log("No match found.");
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

拜托,不要重新发明轮子...

UI5,就像许多其他或多或少成熟的框架一样,利用 Router 范例进行导航。

它给了你更多的自由——你可以使用书签,维护应用程序状态,易于维护,因此你不需要使用难看的 switch / if-then-else 语句.

参见Application Best Practices or have a look at this working example中对路由机制的精彩解释。您可以轻松适应与磁贴一起使用。

(如果我要进行代码审查,并且没有看到用于导航的路由器机制,我会完全删除代码并请您重新开始)

编辑:看来我有点被多个开关误导了……抱歉!

我假设您正在根据模型填充磁贴。那么为什么不将导航目标添加到您的模型中呢?

TileCollection : [
    {
        icon   : "sap-icon://inbox",
        title  : "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        target : "detailView1"
    },
    {
        //etc
    }
]

瓷砖定义:

<TileContainer id="container" tiles="{/TileCollection}">
    <StandardTile
        icon="{icon}"
        title="{title}"
        press="handlePress" />
</TileContainer>

您的事件处理程序为您的所有图块提供 press 事件,然后可以像这样简单:

handlePress: function(oEvent) {
    var sTarget = oEvent.getSource().getBindingContext().getObject().target;
    this.oRouter.navTo(sTarget);
}

希望这能解释更多! :)