UI5_Data Binding

No Data Binding

在页面上创建一个Text控件如下,text为固定文本

new sap.m.Text({text: "Hi, my name is Harry Hawk"}).
        placeAt("content");

Creating Model

创建JSON Model,并通过setModel方法绑定。创建Text控件时可以用{/greetingText}取出值。

sap.ui.getCore().attachInit(function () {
    // Create a JSON model from an object literal
    var oModel = new sap.ui.model.json.JSONModel({
        greetingText: "Hi, my name is Harry Hawk"
    });
    // Assign the model object to the SAPUI5 core
    sap.ui.getCore().setModel(oModel);
    // Create a text UI element that displays a hardcoded text string
    new sap.m.Text({text: "{/greetingText}"})
        .placeAt("content");
});

Two-Way Data Binding

创建控件如下,两个input控件的enabled属性都绑定到Model,同时CheckBox控件的selected属性也绑定到这个Model,当selected取消勾选时,enabled值变为false,因此input控件的enabled属性值同时更新成false,input控件变为不可输入。

    <content>
      <Label text="First Name" class="sapUiSmallMargin" />
      <Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
      <Label text="Last Name" class="sapUiSmallMargin" />
      <Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
      <CheckBox selected="{/enabled}" text="Enabled" />
    </content>

One-Way Data Binding

创建JSON Model后,oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay);将其设为One-Way Data Binding,数据从模型实例到使用者(通常控件的属性)单向传输,使用者值改变后不返回给模型实例。如下例子中,将selected取消勾选时,enabled模型值没有更新,input控件的enabled属性值仍为true。

Resource Models

创建 /i18n/i18n.properties 文件,在script中创建ResourceModel并绑定。

      var oResourceModel = new sap.ui.model.resource.ResourceModel({
        bundleName : "sap.ui.demo.db.i18n.i18n"
      });
      sap.ui.getCore().setModel(oResourceModel, "i18n");

在xml view中,可以通过text="{i18n>firstName}"来读取。url添加后缀?sap-language=de可以显示相应的语言

Accessing Properties in Hierarchically Structured Models

通过'/'访问Model中的层级 text="{/address/street}\n{/address/zip} {/address/city}\n{/address/country}"

Formatting Values

新建Link控件,parts为传入的参数,是由path对象组成的数组,formatter为触发的事件,带上parts中的参数,.formatMail前面的点号表示当前controller下寻找,没有点号表示寻找全局。

<Link class="sapUiSmallMarginBegin"
        href="{
                parts: [
                    '/firstName',
                    '/lastName'
                ],
                formatter: '.formatMail'
            }"
        text="{i18n>sendEmail}"/>

controller中定义事件的实现方法

    return Controller.extend("sap.ui.demo.db.controller.App", {
        formatMail: function(sFirstName, sLastName) {
            var oBundle = this.getView().getModel("i18n").getResourceBundle();
            return sap.m.URLHelper.normalizeEmail(
                sFirstName + "." + sLastName + "@example.com",
                oBundle.getText("mailSubject", [sFirstName]),
                oBundle.getText("mailBody"));
        }
    });

点击链接,会发送Email


Property Formatting Using Data Types

对于数值类型的value可以直接用下面的方法进行格式化,path为数字与单位的路径,type选择类型,showMeasure: false不显示单位

value="{ parts: [{path: '/salesToDate'}, {path: '/currencyCode'}], 
         type: 'sap.ui.model.type.Currency', 
         formatOptions: {showMeasure: false } }"

Validation Using the Message Manager

对于金额等字段UI5中可以自动进行校验,如有错误通过 Message Manager 显示错误信息。创建view后将其注册到Message Manager

var oView = new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.view.App" });
sap.ui.getCore().getMessageManager().registerObject(oView, true);
oView.placeAt("content");

当输入字段有误时,会显示错误信息


Aggregation Binding Using Templates

List 控件为template control。创建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": true
    }]
  }

创建JSON Model加载Products.json,并将其绑定到products Model

var oProductModel = new sap.ui.model.json.JSONModel();
oProductModel.loadData("./model/Products.json");
sap.ui.getCore().setModel(oProductModel, "products");

在view中创建list控件,指定其item为<List headerText="{i18n>productListTitle}" items="{products>/Products}">在items标签中,访问相应字段

<items>
  <ObjectListItem title="{products>ProductName}"

Element Binding

在view中添加显示行信息的控件,在list控件中添加press事件press=".onItemSelected" type="Active",在controller中实现该事件。oEvent.getSource获取点击的item行控件,getBindingContext("products")获取绑定的products上下文,path形式为/Products/0。获取显示详细行的productDetailsPanel控件,bindElement方法绑定model及path。

onItemSelected: function(oEvent) {
            var oSelectedItem = oEvent.getSource();
            var oContext = oSelectedItem.getBindingContext("products");
            var sPath = oContext.getPath();
            var oProductDetailPanel = this.getView().byId("productDetailsPanel");
            oProductDetailPanel.bindElement({ path: sPath, model: "products" });
        }

Expression Binding

添加Expression BindingnumberState="{= ${products>UnitPrice} > ${/priceThreshold} ? 'Error' : 'Success' }"
表达式绑定可以写成{=expression}(Two way)或{:=expression}(One way),表达式中取model数据用${products>UnitPrice}的方式。对于如numberState="{= ${products>UnitPrice} <= ${/priceThreshold} ? 'Success' : 'Error' }"中的<=,不能直接用,需进行转义<=

Aggregation Binding Using a Factory Function

将List改为如下形式,通过factory function来建立item

            <List id="ProductList" headerText="{i18n>productListTitle}" items="{
                path: 'products>/Products',
                factory: '.productListFactory'
            }" />

controller中实现productListFactory,可以通过oContext.getProperty("ProductName")获取属性值,通过如下创建控件

oUIControl = new sap.m.ObjectListItem(sId, {
                    title : sDescription,
                    number : {
                        parts : [ "products>UnitPrice", "/currencyCode" ],
                        type : "sap.ui.model.type.Currency",
                        formatOptions : {
                            showMeasure : false
                        }
                    },
                    numberUnit : {
                        path : "/currencyCode"
                    }
                });

通过如下添加press事件,最后return oUIControl返回创建的控件。

oUIControl.setType(sap.m.ListType.Active);
oUIControl.attachPress(this.onItemSelected, this);
return oUIControl;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,738评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,377评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,774评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,032评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,015评论 5 361
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,239评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,724评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,374评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,508评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,410评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,457评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,132评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,733评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,804评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,022评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,515评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,116评论 2 341

推荐阅读更多精彩内容