我正在尝试创建一个具有通用方法和通用 onInit
逻辑的基本 Controller 。
使用 extend
方法将方法从基础 Controller 添加到子 Controller ,但生命周期方法被完全覆盖。
- 我尝试使用 this documentation page 上显示的
override.onInit
方法但它没有用。 - 我还尝试使用
sap.ui.component
like this但我根本无法让它工作。
我不确定它是否适用于 AMD 语法。
据我所知,扩展功能应该替换已被重写的通用方法,但它应该按照各自的顺序从基础 Controller 和扩展 Controller 执行生命周期方法。
所以我的问题如下:
- 这种行为有可能实现吗?如果是这样,我做错了什么?
- 有没有更好的实现方式?
示例代码:
父 Controller
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("my.namespace.controller.App", {
onInit: function () {
console.log("reusable init");
},
// ...
});
});
子 Controller
sap.ui.define([
"my/namespace/controller/App.controller"
], function (Controller) {
"use strict";
return Controller.extend("my.namespace.child.controller.App", {
onInit: function () {
console.log("extend init");
},
// ...
});
});
此示例仅在我运行应用程序时记录“extend init”。我希望它按此顺序同时记录“可重用初始化”和“扩展初始化”。
我省略了一些代码,但主要思想在这两个 Controller 上得到了体现。唯一相关的元数据是基本 Controller 是抽象的。
最佳答案
在许多情况下,当从头开始开发应用程序时,BaseController 方法就足够了,正如 Benedikt 解释的那样,或者您可以尝试使用许多微型模块进行组合,具体取决于您的项目。
主题 Controller 扩展鲜为人知,但值得了解它的内容以及扩展如何帮助我们进行应用程序开发。
该文档确实暗示扩展概念通常针对想要使用附加功能扩展现有 应用程序的开发人员。但扩展也可用于在您自己的应用程序开发中重用某些逻辑。
[Controller extensions] can be used [...] as a reusable part that is added to the original application. (Source)
目前有两种做法:
名为 "Component Configuration" 的旧概念
(扩展在manifest.json
或以前在Component.js
中声明)- 受旧版 UI5 支持。
- 生命周期方法被称为补充原始方法(见下表)。
- 具有相同名称的非生命周期方法被扩展完全覆盖。
- 简单且声明式,但无法定义清晰的接口(interface),哪些方法可以按哪些顺序扩展。
参见,this plunk例如。
新概念称为 "Controller Extension"
(使用模块"sap/ui/core/mvc/ControllerExtension"
和methods
section within controller'smetadata
)- 自 1.56 以来公开记录但 no samples so far .
- 生命周期方法在原始方法的之外被调用(Same 作为旧方法)。
- 提供定义清晰界面的可能性:
- 可见性(
public: true | false
) - 可覆盖性(
final: true | false
) - 执行策略(
overrideExecution: "After"| "Before"| "Instead"
) - 允许通过静态
ControllerExtension.override
方法在基本 Controller 本身中扩展扩展方法。
- 可见性(
- 可用于添加可重用的JS部分(相当于片段概念)。
参见 this plunk例如。
生命周期执行顺序
无论哪种情况,UI5 默认按以下顺序执行生命周期方法:
onInit
onInit
onBeforeRendering
onBeforeRendering
onAfterRendering
onAfterRendering
退出
退出
关于inheritance - Controller 和生命周期方法的 UI5 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67955167/