事件回调后this.getView()返回未定义

时间:2018-07-30 22:16:59

标签: javascript sapui5

在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();
}

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

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

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

编辑:

我通过将视图绑定到变量然后在on click回调中捕获它来解决了这个问题。

let view = this.getView()

然后再

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

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

    controller.func();
} 

1 个答案:

答案 0 :(得分: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

中找到有关自定义控件的更多信息。
相关问题