[英]UI5: how to reuse formatter in other views?
<Text text="{ parts: [ '/firstText', '/number' ], formatter: '.NumberFormatter' }" />
I have this formatter in my XML view which is defined in the controller.我在 controller 中定义的 XML 视图中有这个格式化程序。 It works fine, everything is good.
它工作正常,一切都很好。
How can I reference and use this formatter in another XML view?如何在另一个 XML 视图中引用和使用此格式化程序? To keep it DRY.
保持干燥。
Usually formatters are in their own JS file通常格式化程序在他们自己的 JS 文件中
Your project structure:您的项目结构:
- webapp
|-- controller
|-- First.controller.js
|-- Second.controller.js
|-- util
|-- Formatter.js
|-- view
|-- First.view.xml
|-- Second.view.xml
|-- Component.js
|-- index.html
Your Formatter.js might look like this您的 Formatter.js 可能看起来像这样
sap.ui.define([], function () {
"use strict";
return {
NumberFormatter: function (sText, iNumber) {
...
},
MyOtherFormatter: function(...) {
...
}
};
});
Now every controller has to reference the Formatter to make it available in your view.现在每个 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 () {
...
}
});
});
Finally you can use it in your view最后你可以在你的视图中使用它
<m:Text text="{
parts: [
'myModel>firstText',
'myModel>/number'
],
formatter: '.formatter.NumberFormatter'
}" />
See Step 23 of the highly recommended official walkthrough which answers 95% of all beginner questions!请参阅强烈推荐的官方演练的第 23 步,它回答了所有初学者问题的 95%!
Make the formatter as a pure ?使格式化程序成为纯粹的? static function module:
static function模块:
sap.ui.define([ // Eg in "./model/numberFormatter.js" //... ], function(/*...*/) { "use strict"; //... return function(/*...*/) { return /*...*/; }; });
Require and use that formatter anywhere you want.在您想要的任何地方都需要并使用该格式化程序。 For example, in the view definition using the
core:require
-syntax (supported as of UI5 1.69):例如,在视图定义中使用
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>
Unless the formatter doesn't require a controller reference, encapsulating it as shown above keeps the controller code clean and the formatter also becomes easier to unit-test.除非格式化程序不需要 controller 参考,否则如上所示封装它可以保持 controller 代码干净并且格式化程序也变得更容易进行单元测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.