Custom Formatters
如果我们想用更复杂的逻辑来格式化数据模型的属性,我们还可以编写自定义格式化函数。现在,我们将使用自定义格式化程序添加本地化状态,因为数据模型中的状态是一种技术性很强的格式。
Coding
webapp/model/formatter.js (新建)
sap.ui.define([], function () {
"use strict";
return {
statusText: function (sStatus) {
var resourceBundle = this.getView().getModel("i18n").getResourceBundle();
switch (sStatus) {
case "A":
return resourceBundle.getText("invoiceStatusA");
case "B":
return resourceBundle.getText("invoiceStatusB");
case "C":
return resourceBundle.getText("invoiceStatusC");
default:
return sStatus;
}
}
};
});
我们在应用程序项目中创建一个新的文件夹模型。新的格式化程序文件被放置在应用程序的model文件夹中,因为格式化程序正在处理数据属性并格式化它们以便在UI上显示。到目前为止,除了发票之外,我们没有任何与模型相关的工件。这一次,我们不从任何基对象进行扩展,而是在sap.ui.define调用中返回一个带有格式化器函数的JavaScript对象。
函数statusText从数据模型获取技术状态作为输入参数,并返回从resourceBundle文件读取的可读文本。
webapp/controller/InvoiceList.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"../model/formatter"
], function (Controller, JSONModel, formatter) {
"use strict";
return Controller.extend("sap.ui.demo.walkthrough.controller.InvoiceList", {
formatter: formatter,
onInit : function () {
var oViewModel = new JSONModel({
currency: "EUR"
});
this.getView().setModel(oViewModel, "view");
}
});
});
要加载我们的格式化器函数,我们必须将它添加到InvoiceList.controller.js中。在这个控制器中,我们首先向自定义formatter模块添加一个依赖项。控制器只是将加载的格式化器函数存储在本地属性格式化器中,以便能够在视图中访问它们。
webapp/view/InvoiceList.view.xml
<mvc:View
controllerName="sap.ui.demo.walkthrough.controller.InvoiceList"
xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc">
<List
headerText="{i18n>invoiceListTitle}"
class="sapUiResponsiveMargin"
width="auto"
items="{invoice>/Invoices}">
<items>
<ObjectListItem
title="{invoice>Quantity} x {invoice>ProductName}"
number="{
parts: [{path: 'invoice>ExtendedPrice'}, {path: 'view>/currency'}],
type: 'sap.ui.model.type.Currency',
formatOptions: {
showMeasure: false
}
}"
numberUnit="{view>/currency}"
numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Success' }">
<firstStatus>
<ObjectStatus text="{
path: 'invoice>Status',
formatter: '.formatter.statusText'
}"/>
</firstStatus>
</ObjectListItem>
</items>
</List>
</mvc:View>
我们使用firstStatus聚合向ObjectListItem 添加一个状态,该状态将显示发票的状态。使用绑定语法的保留属性格式化器指定自定义格式化器函数。格式化程序名称前面的“.”表示在当前视图的控制器中查找该函数。在那里,我们定义了一个属性formatter来保存我们的formatter函数,所以我们可以通过.formatter. statusText访问它。
webapp/i18n/i18n.properties
# App Descriptor
appTitle=Hello World
appDescription=A simple walkthrough app that explains the most important concepts of SAPUI5
# Hello Panel
showHelloButtonText=Say Hello
helloMsg=Hello {0}
homePageTitle=Walkthrough
helloPanelTitle=Hello World
openDialogButtonText=Say Hello With Dialog
dialogCloseButtonText=Ok
# Invoice List
invoiceListTitle=Invoices
invoiceStatusA=New
invoiceStatusB=In Progress
invoiceStatusC=Done
我们向资源包中添加三个新条目,以反映翻译后的状态文本。这些文本现在根据发票的状态显示在ObjectListItem 的number属性下面。
Preview
状态现在显示与自定义格式化程序