我可以知道使用时的差异和性能吗:
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
的
源代码:
Controller.prototype.byId = function(sId) { return this.oView ? this.oView.byId(sId) : undefined; };
...
this.byId
只是 this.getView().byId
的快捷方式。它们都可以用来 访问视图中定义的控件。 例如:
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m">
<!-- ... -->
<Panel id="myPanel" />
<!-- ... -->
</mvc:View>
myControllerMethod: function (/*...*/) {
const thatPanel = this.byId("myPanel"); // === this.getView().byId("myPanel")
},
sap.ui.getCore().byId
怎么样?this.byId
与
sap.ui.getCore().byId
交换。
sap.ui.getCore().byId("someComponent---myView--myPanel"); // <-- Don't!
通常,在开发将添加到应用程序容器(例如 SAP Fiori launchpad (FLP))的 UI5 应用程序时,应避免sap.ui.getCore().byId
。避免
sap.ui.getCore().byId
API
createId("newPanel")
应与
"newPanel"
一起用作本地 ID,而不是全局 ID:new Panel({
// Given this === Controller or View instance
id: this.createId("newPanel") // makes it accessible via this.byId("newPanel")
});
摘自主题“JavaScript 编码问题”部分
“不要创建全局 ID”:
[...]您必须不为 OpenUI5 中的控件、片段或视图创建稳定的 ID。这样做可能会导致重复的 ID 错误,从而破坏您的应用程序。特别是与其他应用程序一起运行时,可能会出现名称冲突或其他错误。 请使用视图或控制器的
createId()
函数。这是在 XMLViews [...] 中自动完成的。createId()
函数添加View ID作为前缀,从而递归地确保ID的唯一性。 如果你确实必须使用
sap.ui.getCore().byId
(自 UI5 1.119 起已被弃用),
需要
sap/ui/core/Element
并调用 Element.getElementById
(自 1.119 起)或 Element.registry.get
(自 1.67 起)。我想到的一个有效用例是访问当前聚焦的控件时,通过
getCurrentFocusedControlId()
检索 ID,直到 UI5 版本低于 1.119。从 1.119 开始,可以通过
Element.getActiveElement()
访问当前焦点控制。对于所有其他情况,应用程序开发中通常有更好的方法。例如,您可能想要监听 routePatternMatched
或 ,然后通过 oEvent.getParameter("view").byId
访问该元素,而不是尝试通过全局元素注册表访问同一元素。有关 ID 的更多信息
文档主题:稳定 ID:您需要了解的一切
byId
byId
直接访问控件,而是考虑通过数据绑定
SAP Fiori 元素 指南
byId
:
[...]
不要访问或操纵 SAP Fiori 元素的内部编码。 [...]
不得访问任何未在您的
视图扩展中定义的 UI 元素。 ⚠注意 如果您不遵守此指南,您的应用程序可能无法与未来的 SAPUI5 版本一起使用,因为 SAP Fiori 元素可能会将控件交换为具有不同 API 的新元素。