更新 UI5 中的模型,使用格式化程序时双向数据绑定变为单向数据绑定

2024-03-19

在我的 UI5 应用程序中,我有一个表,其中每行包含一个sap.m.Switch https://sapui5.hana.ondemand.com/#/api/sap.m.Switch,它通过以下方式绑定到模型formatter https://sapui5.hana.ondemand.com/#/topic/07e4b920f5734fd78fdaa236f26236d8,因为数据来自数据库1/0, 而不是true/false,这可能会打破默认设置双向数据绑定 https://sapui5.hana.ondemand.com/#/topic/c72b922fdb59422496661000165d7ff1.

为了根据此开关的编辑值更新数据模型,我实现了以下内容change https://sapui5.hana.ondemand.com/#/api/sap.m.Switch/events/change-event:

onChangeSwitch: function onChangeSwitch(oEvent) {
    let context = oEvent.oSource.getBindingContext();
    let itemIndex = context.sPath.substr(1);
    let oModel = this.getView().byId("idTablePersons").getModel();
    oModel.oData[itemIndex].isPersonActive = (oEvent.mParameters.state) ? 1 : 0;
    oModel.refresh();
}

它确实有效,但我不确定这是否是实现这种逻辑的正确方法。更改后是否有更新模型的标准方法sap.m.Switch value?


我认为你处理这个问题的方式是错误的。sap.m.Switch已经有一个属性来指示可以直接绑定到模型的状态。

<Switch state="{IsPersonActive}" />

假设您将表中的项目绑定到未命名的模型,这将设置IsPersonActive绑定线上的标志true or false取决于开关的状态。

这也意味着如果确定的话,开关会处于正确的状态IsPersonActive实体集中的标志已设置为 true 或 false。


(…) 数据来自数据库1/0, 而不是true/false (…).
更改后是否有更新模型的标准方法sap.m.Switch value?

双向数据绑定修复https://embed.plnkr.co/wwQXf8bTuiTP4RlP https://embed.plnkr.co/wwQXf8bTuiTP4RlP?show=index.html,model%2Ftype%2FNumericBoolean.js,preview:

数字布尔值.js(最小示例):

sap.ui.define([
  "sap/ui/model/SimpleType",
], Type => Type.extend('demo.model.type.NumericBoolean', {
  constructor: function() {
    Type.apply(this, arguments);
  },
  formatValue: iValue => !!+iValue,
  parseValue: bValue => bValue ? 1 : 0,
  validateValue: vValue => { /*validate...*/ },
}));
<Switch xmlns="sap.m" xmlns:core="sap.ui.core"
  core:require="{ NumericBoolean: 'demo/model/type/NumericBoolean' }"
  state="{
    path: '/1or0',
    type: 'NumericBoolean'
  }"
/>

重要的提示:
必须保留validateValue即使未提供实现也需声明,否则sap.m.Switch将无法正常工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更新 UI5 中的模型,使用格式化程序时双向数据绑定变为单向数据绑定 的相关文章

随机推荐