SAPUI5 (15) - 绝对绑定和相对绑定

回顾一下property binding的使用方法:

sap.ui.getCore().attachInit(function(){				
	
	var oData = {
		"company" : {
			"name"  : "Acme Inc.",
			"street": "23 Franklin St.", 
			"city"  : "Claremont",
			"state" : "New Hampshire",
			"zip"	: "03301",
			"revenue": "1833990"
		}
	};
	
	var oModel = new sap.ui.model.json.JSONModel();
	oModel.setData(oData);
	
	sap.ui.getCore().setModel(oModel);
	
	new sap.m.Input({
		value: "{/company/name}"
	}).placeAt("content");
	
});	// end of attachInit()			

sap.m.Input的通过property binding将value属性绑定到json model根目录下company/name。这是一个绝对绑定的例子。如果我们同时又多个信息需要显示,使用绝对绑定应该是这样:

	new sap.m.Panel({
		headerText: "Company Information",
		content: [
		     new sap.m.Label({text: "Company name"}),
		     new sap.m.Input({value: "{/company/name}"}),
		     
		     new sap.m.Label({text: "Company street"}),
		     new sap.m.Input({value: "{/company/street}"}),
		     
		     new sap.m.Label({text: "City"}),
		     new sap.m.Input({value: "{/company/city}"})
		          
		]
	}).placeAt("content");

每个控件都独立的用绝对路径绑定到model。这样写是不是感觉很啰嗦?sapui5提供一种机制,当父控件的绑定路径设置后,子控件可以基于这个路径使用相对路径。比如将Panel控件的绑定路径设为/company,则子控件都可以基于这个相对路径:

	var oPanel = new sap.m.Panel({
		content: [
		    new sap.m.Label({text: "Company name"}),
		    new sap.m.Input({value: "{name}"}),
		    new sap.m.Label({text: "Street"}),
		    new sap.m.Input({value: "{street}"}),
		    new sap.m.Label({text: "City"}),
		    new sap.m.Input({value: "{city}"}),
		]		 
	});
	
	oPanel.bindElement("/company");	
	oPanel.placeAt("content");	

oPanel.bindElement("/company"); 设置了元素绑定的路径,所以Panel中的控件就可以基于/company这个相对路径进行绑定。相对绑定尤其适用于布局(layout)控件或者容器控件

xml view的相对绑定

上面的例子如果使用xml view,方法如下:

<core:View xmlns:core="sap.ui.core" 
		   xmlns:mvc="sap.ui.core.mvc" 
		   xmlns="sap.m"
		   xmlns:html="http://www.w3.org/1999/xhtml">
		   
	<Panel headerText="Company information" binding="{/company}">
		<Label text="Company name"/>
		<Input value="{name}" />
		<Label text="Street"/>
		<Input value="{street}" />
		<Label text="City"/>
		<Input value="{city}" />	
	</Panel>
	
</core:View>

设置Panel的binding属性:binding="{/company}"

Application area代码:

sap.ui.getCore().attachInit(function(){				
	
	var oData = {
		"company" : {
			"name"  : "Acme Inc.",
			"street": "23 Franklin St.", 
			"city"  : "Claremont",
			"state" : "New Hampshire",
			"zip"	: "03301",
			"revenue": "1833990"
		}
	};
	
	var oModel = new sap.ui.model.json.JSONModel();
	oModel.setData(oData);
	
	sap.ui.getCore().setModel(oModel);
	
	jQuery.sap.registerModulePath("bindingtest", "./webapp");
	var oView = sap.ui.xmlview({
		viewName: "bindingtest.view.relativebinding"
	});

	oView.placeAt("content");
	
});	

你可能感兴趣的:(SAPUI5)