【发布时间】:2023-03-24 22:15:02
【问题描述】:
我使用的时候能知道区别和性能吗:
const myControl = this.getView().byId("myIDhere");
const myControl = this.byId("myIDhere");
const myControl = sap.ui.getCore().byId("myIDhere");
当我在 UI5 应用程序中使用 XML 视图时,哪三个最适合用于对控件执行操作?
【问题讨论】:
我使用的时候能知道区别和性能吗:
const myControl = this.getView().byId("myIDhere");
const myControl = this.byId("myIDhere");
const myControl = sap.ui.getCore().byId("myIDhere");
当我在 UI5 应用程序中使用 XML 视图时,哪三个最适合用于对控件执行操作?
【问题讨论】:
this.getView().byId和this.byId(推荐)看看this.byId方法的source code:
// sap.ui.core.mvc.Controller Controller.prototype.byId = function(sId) { return this.oView ? this.oView.byId(sId) : undefined; };
如您所见,this.byId 只是this.getView().byId 的快捷方式。它们都可以用于访问视图中定义的控件。例如:
<!-- Given -->
<Panel id="myPanel" />
myControllerMethod() {
const thatPanel = this.byId("myPanel"); // === this.getView().byId("myPanel")
},
sap.ui.getCore().byId(不要用)另一方面,API sap.ui.getCore().byId(/*...*/) 等待一个完全连接的 全局 ID,这就是为什么如果目标控件不能简单地将 this.byId 与 sap.ui.getCore().byId 交换是视图后代。
sap.ui.getCore().byId("__xmlview0--myPanel"); // <strong><-- Avoid</strong> concatenating ID parts!
通常,在开发将添加到 Fiori 启动板 (FLP) 的 UI5 应用程序时,应避免使用 sap.ui.getCore()。 IE。在控制器中实例化控件时,请记住使用API createId:
new Panel("myPanel");
new Panel(<strong>this.createId(</strong>"myPanel"<strong>)</strong>); // Makes it accessible via this.byId("myPanel")
来自话题"JavaScript Coding Issues" section "Don't create global IDs":
[...]您必须不为 OpenUI5 中的控件、片段或视图创建稳定的 ID。这样做可能会导致重复的 ID 错误,从而破坏您的应用程序。尤其是与其他应用程序一起运行时,可能会出现名称冲突或其他错误。
改用视图或控制器的
createId()函数。这是在 XMLViews 和 JSONViews 中自动完成的。createId()函数将 View ID 添加为前缀,从而递归地确保 ID 的唯一性。
【讨论】: