![](/img/trans.png)
[英]How to implement a SAP UI5 - Cell Formatter in ListReport Template
[英]UI5: how to reuse formatter in other views?
<Text text="{ parts: [ '/firstText', '/number' ], formatter: '.NumberFormatter' }" />
我在 controller 中定义的 XML 视图中有这个格式化程序。 它工作正常,一切都很好。
如何在另一个 XML 视图中引用和使用此格式化程序? 保持干燥。
通常格式化程序在他们自己的 JS 文件中
您的项目结构:
- webapp
|-- controller
|-- First.controller.js
|-- Second.controller.js
|-- util
|-- Formatter.js
|-- view
|-- First.view.xml
|-- Second.view.xml
|-- Component.js
|-- index.html
您的 Formatter.js 可能看起来像这样
sap.ui.define([], function () {
"use strict";
return {
NumberFormatter: function (sText, iNumber) {
...
},
MyOtherFormatter: function(...) {
...
}
};
});
现在每个 controller 都必须引用 Formatter 以使其在您的视图中可用。
sap.ui.define([
"sap/ui/core/mvc/Controller",
"../util/Formatter"
], function (Controller, Formatter) {
"use strict";
return Controller.extend("demo.controller.First", {
formatter: Formatter, // < Important
onInit : function () {
...
}
});
});
最后你可以在你的视图中使用它
<m:Text text="{
parts: [
'myModel>firstText',
'myModel>/number'
],
formatter: '.formatter.NumberFormatter'
}" />
请参阅强烈推荐的官方演练的第 23 步,它回答了所有初学者问题的 95%!
使格式化程序成为纯粹的? static function模块:
sap.ui.define([ // Eg in "./model/numberFormatter.js" //... ], function(/*...*/) { "use strict"; //... return function(/*...*/) { return /*...*/; }; });
在您想要的任何地方都需要并使用该格式化程序。 例如,在视图定义中使用core:require
-syntax (从 UI5 1.69 开始支持):
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:core="sap.ui.core" core:require="{ myFormatter: 'mynamespace/model/numberFormatter' }"> <Text text="{ parts: [/*...*/], formatter: 'myFormatter' }" /> </mvc:View>
除非格式化程序不需要 controller 参考,否则如上所示封装它可以保持 controller 代码干净并且格式化程序也变得更容易进行单元测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.