如何在SAP UI5 Bootstrap实现中获取组件加载完成的回调?
解决方案
你可以通过两种常用方式,在组件加载完成后触发回调并获取组件实例:
方式1:监听全局组件创建事件
在你的自定义bootstrap模块中,加载sap/ui/core/ComponentSupport的同时,注册全局的componentCreated事件,所有组件初始化完成后都会触发该回调,你可以按需过滤目标组件:
sap.ui.require([ 'sap/ui/core/ComponentSupport', 'sap/ui/core/Core' ], function(ComponentSupport, Core) { // 监听组件创建完成事件 Core.attachComponentCreated(function(oEvent) { var oComponent = oEvent.getParameter('component'); // 根据组件名称过滤你需要的目标组件 if (oComponent.getMetadata().getName() === 'your.target.Component') { // 执行你的逻辑,比如操作组件实例 console.log('组件已初始化:', oComponent); } }); });
方式2:给组件容器绑定局部回调
如果页面中是通过div data-sap-ui-component标签声明组件的,可以直接在标签上添加data-sap-ui-onComponentCreated属性,指定回调模块:
- 页面中的组件声明:
<div data-sap-ui-component data-sap-ui-id="myComponentContainer" data-sap-ui-name="your.target.Component" data-sap-ui-onComponentCreated="module:my/custom/componentCreatedCallback" ></div>
- 自定义回调模块
my/custom/componentCreatedCallback.js:
return function(oComponent) { // 直接获取当前初始化完成的组件实例 console.log('目标组件已初始化:', oComponent); // 编写你的业务逻辑 };
注意事项
- 若使用UI5 1.71及更早版本,全局组件创建事件需通过
Core.getEventBus().subscribe("componentCreated", ...)来监听 - 方式2的
data-sap-ui-onComponentCreated是ComponentSupport原生支持的属性,回调会自动接收组件实例作为参数
内容的提问来源于stack exchange,提问作者Pieter
相关产品推荐
相关产品推荐

