[英]Retrieving the id from a control to use in navigation
我有一个带有磁贴的视图,每个磁贴都有一个id="foo"
属性,以及一个指向控制器中函数的press属性。
问题是我可以获取图块的ID,但是它会自动附加到视图名称__xmlview1--foo1
。 如果已经创建了其他视图,则可以更改。 无法保证它将始终是xmlview1,可以是xmlview2或更高的数字。
如何检索显示在图块的id属性中的纯id? 此switch语句是执行导航的最佳方法,还是有更健壮/优雅的解决方案?
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
,然后只需从--
子字符串_xmlviewX--myviewX
,然后导航到该链接。
请不要试图重新发明轮子 ...
就像许多其他或多或少成熟的框架一样,UI5利用Router
范式进行导航。
它为您提供了更多的自由-您可以使用书签,维护应用程序状态,易于维护,因此您无需使用难看的switch
/ if-then-else
语句。
请参阅“ 应用程序最佳实践”中对路由机制的出色解释,或查看此工作示例 。 您可以轻松地适应与瓷砖一起使用。
(如果我要进行代码审查,但看不到用于导航的路由器机制,则将全部删除代码,并要求您重新开始)
编辑:似乎我被多个开关误导了...我的歉意!
我假设您是根据模型填充图块。 那么,为什么不将导航目标添加到模型中呢?
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
为所有图块提供press
事件的事件处理程序可以很简单:
handlePress: function(oEvent) {
var sTarget = oEvent.getSource().getBindingContext().getObject().target;
this.oRouter.navTo(sTarget);
}
希望这能解释更多! :)
最简单的解决方案是放弃切换,而是使用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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.