首页 > 解决方案 > UI5中更新模型,使用formatter时双向数据绑定变成单向

问题描述

在我的 UI5 应用程序中,我有一个表,其中每行包含一个sap.m.Switch,它通过 绑定到模型formatter,因为数据来自数据库,而不是1/ ,并且可能会破坏默认的双向数据绑定0truefalse

为了根据此开关的编辑值更新数据模型,我实现了以下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

标签: data-bindingsapui5

解决方案


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

<Switch state="{IsPersonActive}" />

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

这也意味着如果IsPersonActive您的实体集中的某些标志已设置为 true 或 false,它将以正确的状态显示开关。


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

来自https://embed.plnkr.co/wwQXf8bTuiTP4RlP的双向数据绑定修复:

NumericBoolean.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'
  }"
/>

重要提示:即使没有提供实现,也
必须保留声明,否则将无法正常工作。validateValuesap.m.Switch


推荐阅读