UI5中更新模型,使用formatter时双向数据绑定变为单向

Mik*_* B. 4 data-binding sapui5

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

为了根据此开关的编辑值更新数据模型,我实现了以下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();
}
Run Code Online (Sandbox Code Playgroud)

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

Jor*_*org 6

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

<Switch state="{IsPersonActive}" />
Run Code Online (Sandbox Code Playgroud)

假设您将表中的项目绑定到一个未命名的模型,这会将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...*/ },
}));
Run Code Online (Sandbox Code Playgroud)
<Switch xmlns="sap.m" xmlns:core="sap.ui.core"
  core:require="{ NumericBoolean: 'demo/model/type/NumericBoolean' }"
  state="{
    path: '/1or0',
    type: 'NumericBoolean'
  }"
/>
Run Code Online (Sandbox Code Playgroud)

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

  • @迈克B。是的,当使用 `formatter` 时,绑定模式变为 `"OneWay"`。为了将它保持在 `"TwoWay"` 中,你必须创建你自己的 `type` _formats_ `1` 和 `0` 为 `true`/`false`,以及 _parses_`true`/`false`作为`1`/`0`。显然,这已经计划好了:https://github.com/SAP/openui5/blob/0adfe5b4aa611d7c5f763c5b16b0ffd4e4ce418a/src/sap.ui.core/src/sap/ui/model/type/Boolean.js#L46。 (4认同)
  • @MikeB 我宁愿让 Jorg 增强他的答案,以便他的答案可以被接受。Jorg:这是您可以为 Mike 添加的一个小示例:https://embed.plnkr.co/wwQXf8bTuiTP4RlP (2认同)