如何在格式化程序中将控制实例设置为 "this"?

How to have control instance as "this" in formatter?

我正在使用 SAP UI5 1.52。我的格式化程序文件是一个单独的文件并加载到控制器中。但是在格式化程序 returns 中记录 this 视图实例而不是控制实例。

我之前参考过 并尝试使用绝对路径并更改了对象在格式化程序中返回的方式。它抛出一个错误,说找不到函数。

UI5 1.69+

查看

<MyControl xmlns:core="sap.ui.core" core:require="{ format: 'demo/model/format' }"
  property="{
    path: '...',
    formatter: 'format'
  }"
/>

格式化程序

sap.ui.define([], function() { // location: "demo/model/format.js"
  "use strict";

  return function(data) {
    // this === control instance
  };
});

从 UI5 1.69 开始,我们可以 require modules directly in the view definition。直接在绑定信息中要求和分配格式化程序让我们可以使用 this 作为相应的控件实例。

  • 无需预先要求控制器中的格式化模块。
  • 无需在全局名称下导出格式化程序。

UI5 1.68及以下

查看

<MyControl property="{
  path: '...',
  formatter: 'demo.model.format'
}" />

格式化程序

sap.ui.define([], function() { // location: "demo/model/format.js"
  "use strict";

  return function(data) {
    // this === control instance
  };
}, /*export*/true); // <-- Enables accessing this module via global name "demo.model.format"

控制器

sap.ui.define([
  "sap/ui/core/mvc/Controller",
  "demo/model/format" // trigger defining the format function module
], function(Controller) {
  // ...

  return Controller.extend("...", {
    // formatter: formatter <-- remove it!
  });
});

在控件的 属性 中,您通常写 formatter:'.formatter.functionName'

只需将其更改为:formatter:'namespace.controllerFolder.controllerName.prototype.formatter.functionName'

并且 this 现在将引用控件实例而不是您的控制器。

简单易行:)