Step 23: Custom Formatters

Step 23: Custom Formatters

https://ui5.sap.com/#/topic/0f8626ed7b7542ffaa44601828db20de
上一节,使用UI5自己的支持表达式绑定的控件实现了,根据价格值的不同,显示不同的颜色。
如果是比较复杂的逻辑,使用表达式绑定就不推荐了,推荐用自定义的代码,来实现了。

webapp/model/formatter.js (New)

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

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

statusText 函数会根据参数sStatus的不同,返回不同的状态的字符串。

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");
		}
	});
});

1,引入../model/formatter文件
2,formatter: formatter,给InvoiceList加一个属性formatter,里面引用的js文件就是webapp/model/formatter.js

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>

1,firstStatus:会在页面上显示【New|In Progress|Done】
2,ObjectStatus text是个表达式
formatter: '.formatter.statusText'是调用的函数。
.formatter:在当前view的controller里找formatter属性,找到后,再调用statusText函数。
path: 'invoice>Status'是函数的参数的值

vx:xiaoshitou5854

posted @ 2021-09-06 08:33  小石王  阅读(436)  评论(0编辑  收藏  举报