this.getView().byId()、this.byId() 和 sap.ui.getCore().byId() 之间的区别

问题描述 投票:0回答:1

我可以知道使用时的差异和性能吗:

const myControl = this.getView().byId("myIDhere");
const myControl = this.byId("myIDhere");
const myControl = sap.ui.getCore().byId("myIDhere");

当我在 UI5 应用程序中使用 XML 视图时,最适合使用三个中的哪一个来对控件执行操作?

sapui5 sap-fiori
1个回答
4
投票

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
怎么样?

API sap.ui.getCore().byId

 等待在 UI5 元素注册表中注册的完全连接的 全局 ID,这就是为什么如果目标控件被定义为视图的一部分,则不能简单地与 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
意味着,在 JavaScript 中实例化新的 UI5 元素时,
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

patternMatched

,然后通过 oEvent.getParameter("view").byId 访问该元素,而不是尝试通过全局元素注册表访问同一元素。
有关 ID 的更多信息
文档主题:

稳定 ID:您需要了解的一切


不要通过

byId
 直接访问控件,而是考虑通过 
数据绑定

操作 UI。模型中的更改将自动反映在 UI 中,并且,如果启用双向绑定,来自 UI 的用户输入将直接存储在模型中。

SAP Fiori 元素 指南


开发 Fiori 元素扩展时,请确保遵守

记录的 兼容性指南

,尤其是关于

byId [...]

不要访问
或操纵 SAP Fiori 元素的内部编码。

[...]
不得访问

任何在您的
视图扩展中定义的 UI 元素。 ⚠注意 如果您不遵守此指南,您的应用程序可能无法与未来的 SAPUI5 版本一起使用,因为 SAP Fiori 元素可能会将控件交换为具有不同 API 的新元素。


© www.soinside.com 2019 - 2024. All rights reserved.