SAPUI5 (14) - 数据绑定之元素绑定(element binding)

元素绑定指根据上下文(binding context)使用相对绑定的方式绑定到model数据的某一具体对象(查看帮助)。尤其适用于**主从数据显示(master-detail data)**的情况。比如我们有一个供应商的清单,当选择供应商的时候,显示该供应商所提供的产品。下面的页面是本篇要实现的功能,当点击左边某一个产品时,在右边显示产品的相关信息:

左边是一个List控件,右边在Panel中放置几个控件组合。当选择左边某个产品的时候,右边相应显示该产品的信息。这就是一个Element Binding的例子。下面介绍实现的方法。先介绍涉及的两个控件。

sap.m.List

The List control provides a container for all types of list items. For mobile devices, the recommended limit of list items is 100 to assure proper performance. To improve initial rendering of large lists, use the “growing” feature. Please refer to the SAPUI5 Developer Guide for more information… (点击查看)

List控件适用于显示行项目,所有类型都可以。对于移动设备来说,出于性能考虑,不要超过100行。使用growing特性可以加速内部的渲染。

List控件继承自sap.m.ListBase,ListBase的items聚合属性(类型:sap.m.ListeItemBase[]) 设置行项目的模板,比如:

new sap.m.List({
    items: {path: '/Products', template: oTemplate}
});

设置List的行项目绑定到json数据的"/Products",行项目模板为oTemplate。oTemplate可以选择合适的控件。也可以使用bindItems方法:

new sap.m.List().bindItems({
	path: '/Products', template: oTemplate
});

sap.m.ObjectListItem

ObjectListItem is a display control that provides summary information about an object as a list item. The ObjectListItem title is the key identifier of the object. Additional text and icons can be used to further distinguish it from other objects. Attributes and statuses can be used to provide additional meaning about the object to the user. (查看原文)

ObjectListItem适用于显示行项目的信息,主要使用title属性进行标识,text、icon、atrributes和statuses等属性可以用于提供对象更多信息。这个控件的属性与ObjectIdentifier比较类似,能够显示的信息也比较多。

这个控件继承自sap.m.ObjectListItem,使用ObjectListItem的press事件,对用户的点击做出回应。

Element Binding示例

数据

本示例数据来自openui5 demo kit。将数据放在products.json文件中。

{ "Products": [ {
     "ProductID": 1,
     "ProductName": "Chai",
     "SupplierID": 1,
     "CategoryID": 1,
     "QuantityPerUnit": "10 boxes x 20 bags",
     "UnitPrice": "18.0000",
     "UnitsInStock": 39,
     "UnitsOnOrder": 0,
     "ReorderLevel": 10,
     "Discontinued": false
    }, {
     "ProductID": 2,
     "ProductName": "Chang",
     "SupplierID": 1,
     "CategoryID": 1,
     "QuantityPerUnit": "24 - 12 oz bottles",
     "UnitPrice": "19.0000",
     "UnitsInStock": 17,
     "UnitsOnOrder": 40,
     "ReorderLevel": 25,
     "Discontinued": false
    }, {
     "ProductID": 3,
     "ProductName": "Aniseed Syrup",
     "SupplierID": 1,
     "CategoryID": 2,
     "QuantityPerUnit": "12 - 550 ml bottles",
     "UnitPrice": "10.0000",
     "UnitsInStock": 13,
     "UnitsOnOrder": 70,
     "ReorderLevel": 25,
     "Discontinued": false
    }, {
     "ProductID": 4,
     "ProductName": "Chef Anton's Cajun Seasoning",
     "SupplierID": 2,
     "CategoryID": 2,
     "QuantityPerUnit": "48 - 6 oz jars",
     "UnitPrice": "22.0000",
     "UnitsInStock": 53,
     "UnitsOnOrder": 0,
     "ReorderLevel": 0,
     "Discontinued": false
    }, {
     "ProductID": 5,
     "ProductName": "Chef Anton's Gumbo Mix",
     "SupplierID": 2,
     "CategoryID": 2,
     "QuantityPerUnit": "36 boxes",
     "UnitPrice": "21.3500",
     "UnitsInStock": 0,
     "UnitsOnOrder": 0,
     "ReorderLevel": 0,
     "Discontinued": true
    }]
  }

代码

代码全部写在index.html中:

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

		<script src="resources/sap-ui-core.js"
				id="sap-ui-bootstrap"
				data-sap-ui-libs="sap.m, sap.ui.layout"
				data-sap-ui-theme="sap_bluecrystal">
		</script>

		<script>		
		
			sap.ui.getCore().attachInit(function(){
				
				// 绑定json数据到core对象
				var oModel = new sap.ui.model.json.JSONModel();
				oModel.loadData("webapp/model/products.json");
				sap.ui.getCore().setModel(oModel);
				
				// 使用ObjectListItem定义行项目的template
				var oTemplate = new sap.m.ObjectListItem({
					title: "{ProductName}",
					type: "Active",
					// 点击的时候设置oPrdDetail.Panel绑定到当前行
					press: function(oEvent){
						var oContext = oEvent.getSource().getBindingContext();
						var sPath = oContext.getPath();

						oPrdDetailPanel.bindElement({path: sPath});	
					}
				});				
					
				// 定义一个Panel,在Panel中放置List, List使用oTemplate
				// 作为行的模板
				var oPrdListPanel = new sap.m.Panel({
					headerText: "产品清单",
					content: [new sap.m.List({
						items: {path: '/Products', template: oTemplate}
					})]
				});
				
				// 明细数据使用垂直布局,每一行包括Label和Input					
				var aProductDetailInfo = new sap.ui.layout.VerticalLayout({
					content: [
						new sap.ui.layout.HorizontalLayout({
							content: [
						    	new sap.m.Label({
						    		text: "Product Id:",width: "150px"
						    	}),
						    	new sap.m.Input({value: "{ProductID}"})
							]
						}),
					
						new sap.ui.layout.HorizontalLayout({
							content: [
						    	new sap.m.Label({
						    		text: "Product Name:",width: "150px"
						    	}),
						    	new sap.m.Input({value: "{ProductName}"})
							]
						}),
					
						new sap.ui.layout.HorizontalLayout({
							content: [
						    	new sap.m.Label({
						    		text: "Quantity Per Unit:",width: "150px"
						    	}),
						    	new sap.m.Input({value: "{QuantityPerUnit}"})
							]
						}),
						
						new sap.ui.layout.HorizontalLayout({
							content: [
						    	new sap.m.Label({
						    		text: "Unit Price:",width: "150px"
						    	}),
						    	new sap.m.Input({value: "{UnitPrice}"})
							]
						})	
					]
				});
				
				var oPrdDetailPanel = new sap.m.Panel("prdDetailPanel", {
					headerText: "产品明细",
					width: "auto",
					content: [aProductDetailInfo]
				});		
				
				new sap.ui.layout.HorizontalLayout({
					content: [oPrdListPanel, oPrdDetailPanel]
				}).placeAt("content");
				
			});				
			
		</script>

	</head>
	<body class="sapUiBody sapUiResponsiveMargin" role="application">
		<div id="content"></div>
	</body>
</html>

代码说明

  • 产品清单数据,使用sap.m.List显示,这是一个聚合绑定。为了能够获取所选择的产品,我们需要有event handler的控件,所以使用sap.m.ObjectListItempress事件获取所选择产品的path:
// 使用ObjectListItem定义一个行项目template
var oTemplate = new sap.m.ObjectListItem({
	title: "{ProductName}",
	type: "Active",
	// 点击的时候设置oPrdDetail.Panel绑定到当前行
	press: function(oEvent){
		var oContext = oEvent.getSource().getBindingContext();
		var sPath = oContext.getPath();

		oPrdDetailPanel.bindElement({path: sPath});	
	}
});		

当用户点击选择的时候,oEvent.getSource().getBindingContext()获取绑定的项,再使用getPath()方法得到path路径,然后设置右边的detailPanel与这个路径绑定。

oEvent是一个sap.ui.base.Event对象,getSouce()方法得到事件的提供者,类型是sap.ui.base.EventProvider

  • 产品明细的信息,使用sap.m.Panel绑定到某一行(bindElement()方法),比如“/Products/0”,然后Panel中的控件使用相对绑定获取要显示的数据。比如:
new sap.m.Input({value: "{UnitPrice}"}

master-detail另一种典型模式

还有一种常见的master-detail模式,就是detail部分为多笔数据。比如定位到某供应商后,查看这个供应商所提供的产品清单。下图是一个示例:

对这种detail包含多笔数据的情况,可以通过filter的方法实现。以下是代码:

supplier_products.json

{
    "suppliers": [
        {
            "id": "1",
            "supplier_name" : "康富食品",
            "contact": "黄小姐"
        }, {
            "id": "2",
            "supplier_name" : "为全",
            "contact": "王先生"
        }, {
            "id": "3",
            "supplier_name" : "康堡",
            "contact": "刘先生"
        }
    ],   
    "products": [
	    {
	        "supplier_id":"1",
	        "product_id":"1",
	        "product_name": "海鲜粉"
	    }, {
	        "supplier_id":"1",
	        "product_id":"2",
	        "product_name": "胡椒粉"
	    }, {
	    	"supplier_id":"1",
	        "product_id":"3",
	        "product_name": "桂花糕"
	    }, {
	    	"supplier_id":"2",
	        "product_id":"1",
	        "product_name": "啤酒"
	    }, {
	    	"supplier_id":"3",
	        "product_id":"1",
	        "product_name": "土豆片"
	    }, {
	    	"supplier_id":"3",
	        "product_id":"2",
	        "product_name": "鸡汤"
	    },{
	    	"meal_no":"2",
	        "day_id":"3",
	        "items": "果仁巧克力"
	    }
    ]
}

index.html

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

		<script src="resources/sap-ui-core.js"
				id="sap-ui-bootstrap"
				data-sap-ui-libs="sap.m, sap.ui.layout, sap.ui.table"
				data-sap-ui-theme="sap_bluecrystal">
		</script>

		<script>		
		
			sap.ui.getCore().attachInit(function(){
				
				// 绑定json数据到core对象
				var oModel = new sap.ui.model.json.JSONModel();
				oModel.loadData("webapp/model/supplier_products.json");
				sap.ui.getCore().setModel(oModel);
				
				// sap.ui.table.Table对象,显示供应商
				var oColumns = [
				    new sap.ui.table.Column({
				    	label: new sap.m.Label({text: "ID"}),
				    	visible: false,
				    	template: new sap.m.Text({text: "{id}"})
				    }),
				    new sap.ui.table.Column({
				    	label: new sap.m.Label({text: "供应商名称"}),
				    	visible: true,
				    	template: new sap.m.Text({text: "{supplier_name}"})
				    }),
				    new sap.ui.table.Column({
				    	label: new sap.m.Label({text: "联系人"}),
				    	visible: true,
				    	template: new sap.m.Text({text: "{contact}"})
				    })
				];
				
				var oSupplierTable = new sap.ui.table.Table({
					width: "100%",
					title: "供应商",
					visibleRowCount: 3,
					selectionMode: sap.ui.table.SelectionMode.Single,
					editable: false,
					columns: oColumns
				});	
				
				oSupplierTable.bindRows("/suppliers");				
				oSupplierTable.placeAt("master");
				
				// 定义sap.ui.table.Table对象,显示供应商的产品
				var oColumnsDetail = [
				    new sap.ui.table.Column({
				    	label: new sap.m.Label({text: "产品ID"}),
				    	visible: true,
				    	template: new sap.m.Text({text: "{product_id}"})
				    }),
				    new sap.ui.table.Column({
				    	label: new sap.m.Label({text: "产品名称"}),
				    	visible: true,
				    	template: new sap.m.Text({text: "{product_name}"})
				    })				    
				];
				
				var oProductTable = new sap.ui.table.Table({
					width: "100%",
					title: "产品",
					visibleRowCount: 3,
					selectionMode: sap.ui.table.SelectionMode.Single,
					editable: false,
					columns: oColumnsDetail
				});	
				
				oProductTable.bindRows("/products");
				oProductTable.placeAt("detail");
				
				// 定义rowselectionchange事件的处理函数
				oSupplierTable.attachRowSelectionChange(function(oEvent){
					// 获取row index
					var oRowContext = oEvent.getParameter("rowContext");
					
					// 根据row index获取model数据中的id
					var sSelectedId = oModel.getProperty("id", oRowContext);					
					
					// 对products中的数据进行过滤
					var oBinding = oProductTable.getBinding();
					
					// 过滤条件:supplier_id = id
					var oFilter = new sap.ui.model.Filter(
							"supplier_id",
							sap.ui.model.FilterOperator.EQ,
							sSelectedId);
					
					// 执行过滤
					oBinding.filter(oFilter);
				});
				
			});	// end of attachInit()			
			
		</script>

	</head>
	<body class="sapUiBody sapUiResponsiveMargin" role="application">
		<div id="master"></div>
		<div id="detail"></div>
	</body>
</html>

代码说明:

  • 供应商表一共3列,但id不显示。
  • 在supplier表的rowselectionChange事件中对products进行筛选:
oSupplierTable.attachRowSelectionChange(function(oEvent){
	// 获取row index
	var oRowContext = oEvent.getParameter("rowContext");
	
	// 根据row index获取model数据中的id
	var sSelectedId = oModel.getProperty("id", oRowContext);					
	
	// 对products中的数据进行过滤
	var oBinding = oProductTable.getBinding();
	
	// 过滤条件:supplier_id = id
	var oFilter = new sap.ui.model.Filter(
			"supplier_id",
			sap.ui.model.FilterOperator.EQ,
			sSelectedId);
	
	// 执行过滤
	oBinding.filter(oFilter);
});

sap.ui.table.Table没有getBindingContext()方法,但包含rowContext属性,所以通过var oRowContext = oEvent.getParameter("rowContext")获取行的上下文,如果选中第一行,rowContext就是constructor {oModel: d, sPath: "/suppliers/0"}。然后通过var sSelectedId = oModel.getProperty("id", oRowContext);就能获取到所选择行的供应商id。

  • 过滤的代码比较直观,请参照代码注释理解。
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值