通过另一个控制器调用函数时无法读取未定义的 属性 'byId'

Cannot read property 'byId' of undefined when calling function through another controller

我有两个控制器和一个 XML 文件。我想从第一个控制器调用第二个控制器的函数。该函数应该更改与第二个控制器关联的 xml 文件的文本。

这就是我从第一个控制器调用第二个控制器函数的方式:

sap.ui.controller("project.controller.one").set("pancakes");

这是第二个控制器中的函数:

set: function (text) {
    alert(text);
    this.getView().byId("label0").setText(text);
}

XML 有一个 Labellabel0id

我收到以下错误:

Uncaught TypeError: Cannot read property 'byId' of undefined

每当我到达这条线时:

this.getView().byId("label0").setText(text)

但是,如果我将它放在控制器二的 onInit 中:

this.getView().byId("label0").setText("bananas")

然后标签将更改为 "bananas" 而不会出现错误。

我错过了什么?

方法 sap.ui.controller returns 一个新的控制器实例,如 documentation 中所述:

If only a name is given, a new instance of the named controller class is returned.

所以它可能 returns 与视图无关的控制器副本,因此它不会找到它。该方法本身也已弃用,因此我一般不建议在较新的 UI5 版本上使用它。

两个控制器之间通信的首选方式是使用 sap.ui.core.EventBus

在第二个控制器中,您首先要 subscribeonInit 中的一个事件,然后将其绑定到一个函数:

onInit: function() {
    sap.ui.getCore().getEventBus().subscribe("Controller2", "set", this.setFromEvent, this);
    // ....
}

第一、二个参数为通道名称和事件名称,可自由选择。第三个参数是要调用的方法,第四个参数将作为该方法内部this的值。

为了触发事件,你可以在你的其他控制器中使用EventBus的publish方法:

sap.ui.getCore().getEventBus().publish("Controller2", "set", { value: "pancakes" });

第一和第二个参数是你上面订阅对应的频道和活动名称。第三个参数是可以发送数据的对象,可以自由选择。

当然,你还需要在第二个控制器中创建setFromEvent方法:

setFromEvent: function(sChannelId, sEventId, oData) {
    this.set(oData.value);
}

该方法的参数与上面传递给publish方法的值相对应。