SAP UI5 setProperty 的执行逻辑单步调式和分析
按照 Jerry 这篇文章介绍的代码,运行之后,给类型为 sap.ui.model.type.Currency
的字段设置一个非 number
类型的值之后,触发该数据类型自带的数据校验机制,显示 Enter a number
的错误消息。
SAP UI5 应用开发教程之四十六 - 使用 Message Manager 实现开箱即用的验证(Validation)信息抛出
本文介绍 SAP UI5 ManagedObject
的 setProperty
方法的执行原理。
首先明确,什么是 ManagedObject
?
托管属性表示 ManagedObject 的状态。 它们可以存储简单数据类型(如“字符串”或“整数”)的单个值。 它们具有名称(例如“size”)和获取当前值(getSize)或设置新值(setSize)的方法。 当通过调用 setter 修改属性时,ManagedObject 被标记为无效。 可以使用 #bindProperty 方法将托管属性绑定到 sap.ui.model.Model 中的属性。 对模型属性的更新将自动反映在托管属性中,并且 - 如果 TwoWay 数据绑定处于活动状态,则对托管属性的更改将反映在模型中。 可以通过调用#unbindProperty 删除现有绑定。

当 input 控件失去 focus 之后,触发 onsapfocusleave
,这个方法调用 onChange
:

传入的输入参数,event
类型为 sapfocusleave
:

如果当前最新的值和之前的值 getLastValue()
不相等,则调用 this.setValue
:

Input.setValue 调用 InputBase.setValue:

setValue 最终调用 setProperty,属性名称为 value
:

正式进入 setProperty 方法,首先从 mProperties
里得到修改之前的值:

然后进行 validateProperty
:

validateProperty 内部,首先从 this.getMetadata().getManagedProperty(sPropertyName)
读取该 value 属性的 元数据
:

关于 SAP UI5 控件的元数据设计,请参考我这篇文章:
深入学习SAP UI5框架代码系列之四:SAP UI5控件的元数据实现。
获得 string 类型对象:

类型对象由一系列函数组成:

执行 normalize 操作:

将这个不合法的 value,设置到 this.mProperties[sPropertyName]
中。

进行双向绑定的逻辑处理:this.updateModelProperty

拿到绑定对象:

进入双向绑定的处理分支:

if (oBinding && oBinding.getBindingMode() == BindingMode.TwoWay) {
oBindingInfo.skipPropertyUpdate++;
SyncPromise.resolve(oValue).then(function(oValue) {
return oBinding.setExternalValue(oValue);
}).then(function() {
oBindingInfo.skipPropertyUpdate--;
return oBinding.getExternalValue();
}).then(function(oExternalValue) {
if (oValue != oExternalValue) {
that.updateProperty(sName);
}
handleSuccess();
}).catch(function(oException) {
oBindingInfo.skipPropertyUpdate--;
handleException(oException);
}).unwrap();

SyncPromise.resolve(oValue).then(function(oValue) {
return oBinding.setExternalValue(oValue);
})

在 CompositeBinding.js
内部,核心逻辑是第 325 行的代码:
that.oType.parseValue(oValue, that.sInternalType, aCurrentValues);

调用 outputFormat
进行输入值的解析工作:
