在我的 UI5 应用程序中,我有一个表格,其中每一行都包含一个 sap.m.Switch
,通过 formatter
绑定(bind)到模型, 因为数据来自数据库 1
/0
,而不是 true
/false
,这可能会破坏默认值 two-way data binding .
为了根据此开关的编辑值更新数据模型,我实现了以下 change
-事件:
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
已经有一个属性来指示您可以直接绑定(bind)到模型的状态。
<Switch state="{IsPersonActive}" />
假设您将表中的项目绑定(bind)到一个未命名的模型,这将设置
IsPersonActive
在绑定(bind)线上标记到 true
或 false
取决于开关的状态。这也意味着,如果某些
IsPersonActive
,它将以正确的状态输出开关。您的实体集中的标志已设置为 true 或 false。(…) the data is coming from the DB as
1
/0
, rather thantrue
/false
(…).
Is there a standard way to update a model after changingsap.m.Switch
value?
来自 https://embed.plnkr.co/wwQXf8bTuiTP4RlP 的双向数据绑定(bind)修复:
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'
}"
/>
重要提示:
必须保留
validateValue
即使没有提供实现也要声明,否则 sap.m.Switch
将无法正常工作。
关于data-binding - UI5中更新模型,使用formatter时双向数据绑定(bind)变成单向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484815/