【问题标题】:this.getView() returns undefined after event callbackthis.getView() 事件回调后返回 undefined
【发布时间】:2018-07-30 22:16:59
【问题描述】:

在我的 ui5 控制器中,我在 onBeforeRending 函数中调用我的方法。在该方法中,我调用了this.getView().getId(),这是我正在使用的库所需要的,这很好:

onBeforeRendering: function () {
    this.func();
}, 

func: function() {
    this.getView().getId();
}

后来,我有一个 html 控件的 onClick 事件处理程序:

click: function () {
    const controller = sap.ui.controller("Project.controller.Controller");
    controller.func();
}

当从controller.func 调用this.getView() 时,出现以下错误:

Uncaught TypeError: Cannot read property 'getId' of undefined
  func
  click 

我意识到这意味着 getView() 返回undefined,但我不知道为什么。在第二次调用中检查 func 内部的 this 引用表明它可以访问控制器中的其他功能,但不能访问 getView

编辑:

我通过将视图绑定到一个变量然后在点击回调中捕获它来解决问题。

let view = this.getView()

后来

click: function() {
    const controller = sap.ui.controller("Project.controller.Controller");

    controller.getView = function () {
        return view;
    };

    controller.func();
} 

【问题讨论】:

  • onClick 处理程序在哪里?这是在自定义控件中吗?我认为您只是在获取一个控制器,如果这是意图,它不会连接到当前视图。
  • @Jorg 如何将它连接到我想要的视图?
  • 所以是自定义控件?答案将取决于它是什么
  • @Jorg 是的,它是一个 highchart.js 图表,但它只是被导入并放置到视图中,并且像普通的 highchart 图表一样运行。没有创建和注册自定义控件。
  • @Jorg 我发现你可以使用sap.ui.xmlview("Project.view.View") 来获取视图,但这似乎会创建一个新视图,并且与当前视图的 id 不同。如何使用正确的 id 获取当前视图?

标签: javascript sapui5


【解决方案1】:

试图回答,因为有很多要坚持的评论。

如果您使用第三方库,将代码包装在自定义控件中通常仍然很有用。之后,该控件可以在各种其他应用程序中重用,并允许从控件外部绑定数据和处理程序,由您放置控件的视图的控制器提供。

此外,如果您使用的是 SAPUI5 而不是 OpenUI5,您将可以访问 VizFrame,它是 D3 的 UI5 包装器(它将一起替换此解决方案)。

这是自定义控件的框架代码。替换路径和命名空间等:

sap.ui.define(
  ['sap/ui/core/Control', '../path/to/highcharts'],
  function(Control) {
    "use strict";

    return Control.extend("my.namespace.graph", {
      metadata: {
          events : {
            "graphClick" : {}
          }
      },

      init: function() {
        //initialisation. 
      },

      renderer: function(element, control) {
        element.write(`<div id="my-graph"></div>`);
      },

      onAfterRendering: function() {
        //do whatever you need to bind a handler to your graph. You can call a function on 
        //this control like this.onClick, below. 
      },

      onClick: function(data) {
        this.fireGraphClick(data);
      }
    });
  });

您可以将此控件导入您的视图并像使用任何其他控件一样使用它。 graphClick 就是你使用的:

<controls:graph graphClick="myControllerFunction" />

别忘了给xml命名空间添加控件...

您可以在UI5 documentation中找到有关自定义控件的更多信息

【讨论】:

  • 事件应该是外部属性。那是元数据的孩子。渲染器功能错误,需要添加控件数据。
  • 我已经移动了事件。老实说,我真的不知道控件数据中有什么,但是添加 ui5 控件类和 ID 可能会影响第三方库。
猜你喜欢
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 2022-10-30
  • 1970-01-01
相关资源
最近更新 更多