有没有办法在组件加载到引导程序实现中后立即获取回调?

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

我正在使用

data-sap-ui-onInit="module:my/custom/bootstrap"
,其实施以
sap.ui.require(['sap/ui/core/ComponentSupport']
结尾。

有没有办法在组件加载到引导程序实现中后立即获取回调?我想在初始化后获得对组件对象的引用。

sapui5
1个回答
1
投票

在不接触

Component.js
内容的情况下,如果您可以控制初始 HTML 文档(此处:
index.html
)和分配给
data-sap-ui-oninit
的 JS 文件(此处:
myBootstrap.js
),您可以将处理程序附加到
 ComponentContainer
的事件,例如
componentCreated
componentFailed
,如下所示:

index.html

<head ...>
  <!-- ... -->
  <script id="sap-ui-bootstrap"
    src="<...>resources/sap-ui-core.js"
    data-sap-ui-async="true"
    data-sap-ui-resourceRoots='{ "my.demo": "./" }'
    data-sap-ui-oninit="module:my/demo/myBootstrap"
    data-sap-ui-...="..."
  ></script>
</head>
<body id="content" class="sapUiBody">
  <!-- Only in UI5 1.x as registering a global event handler in HTML 
  like below is deprecated since UI5 1.120 and removed in UI5 2.x -->
  <div data-sap-ui-component
    data-id="myRootComponentContainer"
    data-name="my.demo"
    data-component-created="onMyComponentCreated"
    data-height="100%"
    data-settings='{ "id": "myRootComponent" }'
    data-...="..."
  ></div>
</body>

myBootstrap.js

// ...
globalThis.onMyComponentCreated = function(event) {
  const myCreatedComponent = event.getParameter("component");
  // ...
};

// === Only in UI5 1.x ===
sap.ui.require(["sap/ui/core/ComponentSupport"]);
// =======================

// === Only in UI5 2.x ===
sap.ui.require([
  "sap/ui/core/ComponentContainer",
], ComponentContainer => new ComponentContainer({
  id: "myRootComponentContainer",
  name: "my.demo",
  componentCreated: globalThis.onMyComponentCreated, // or an anonymous function
  height: "100%",
  settings: { id: "myRootComponent" },
  // Settings that sap/ui/core/ComponentSupport applies by default:
  lifecycle: "Container", // enum sap.ui.core.ComponentLifecycle
  autoPrefixId: true,
  manifest: true,
}).placeAt("content"));
// =======================

这里,处理程序名称“

onMyComponentCreated
”只是一个示例名称。确保创建的名称不会在全局范围内导致名称冲突,或者在手动创建
ComponentContainer
时分配匿名函数。


关于

data-component-created
语法:

由于 HTML 不区分大小写,为了定义具有大写字符的属性,您必须 使用破折号字符“转义”它们。 (来自 API 参考:

sap/ui/core/ComponentSupport

有关更多信息,请查看文档主题 “初始组件的声明式 API”

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