gpt4 book ai didi

event-handling - 具有不同 Controller 的 XML View 的共享事件处理程序

转载 作者:行者123 更新时间:2023-12-03 23:35:53 25 4
gpt4 key购买 nike

给定两个 XML View :

<mvc:View
controllerName="my.namespace.controller.First"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">

<Button press=".onBtnPress" />
</mvc:View>


<mvc:View
controllerName="my.namespace.controller.Second"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">

<Button press=".onBtnPress" />
</mvc:View>

正如预期的那样,按下事件由 First.controller.jsSecond.controller.js 处理。

我不想复制事件处理程序代码或在每个 Controller 中实现处理程序来链接/移交工作,我想声明一个共享事件处理程序。

根据 docs这应该是可能的,使用处理程序的命名约定:

Names starting with a dot ('.') are always assumed to represent a method in the controller.

Names containing a dot at a later position are assumed to represent global functions and are resolved by calling jQuery.sap.getObject with the full name.

所以我更改处理程序并声明一个共享对象,如下所示:

First.view.xml:

<Button press="my.namespace.Shared.onBtnPress" />

Shared.js:

jQuery.sap.declare("my.namespace.Shared");

my.namespace.Shared = (function() {

var onBtnPress = function() {
console.log("button pressed");
};

return { onBtnPress : onBtnPress };
}());

在 View 初始化期间记录警告(调试源):

sap.ui.core.mvc.XMLView#__xmlview1: event handler function "my.namespace.Shared.onBtnPress" is not a function or does not exist in the controller. -

调用 jQuery.sap.getObject("my.namespace.Shared") 产生 undefined

使用 sap.ui.define 使对象已知时出现同样的问题。

最佳答案

自 UI5 1.69 以来,在 XML View 和片段中共享 JS 模块变得更加容易。 doc

这是一个示例:https://embed.plnkr.co/5G80I5HWObCuM5cG

<mvc:View controllerName="..."
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:core="sap.ui.core"
core:require="{ onButtonPress: 'my/shared/onButtonPress' }">
<Button text="Press" press="onButtonPress" />
</mvc:View>

正如我们所见,每个按钮根据 View 显示不同的消息,即使处理程序本身未包含在 Controller 定义中也是如此。

this 上下文仍然是 Controller 实例,如主题 Handling Events in XML Views 中所述:

As long as no event handler parameters are specified and regardless of where the function was looked up, it will be executed with the controller as the context object (this).

关于event-handling - 具有不同 Controller 的 XML View 的共享事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34514335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com