You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SAP UI5 XML视图中复用自定义数据类型的实例

解决方案

方案1:单视图内复用(最简便)

  1. 在对应控制器的onInit生命周期中预创建唯一的类型实例,挂载到控制器实例上:
sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "mynamespace/model/type/Power"
], function(Controller, Power) {
    "use strict";

    return Controller.extend("mynamespace.controller.MainView", {
        onInit: function () {
            // 仅初始化一次,所有控件复用该实例
            this._oSharedPowerType = new Power({
                decimals: 0,
                emptyString: null
            });
        }
    });
});
  1. XML视图中直接通过$controller绑定语法引用已创建的实例,无需重复配置formatOptions,也不会生成新的类型实例:
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"
    xmlns="sap.m" 
    controllerName="mynamespace.controller.MainView">

    <Input id="InputA" value="{
        path : 'model>powerA', 
        type : ${controller>/._oSharedPowerType}
    }" />
                            
    <Input id="InputB" value="{
        path : 'model>powerB', 
        type : ${controller>/._oSharedPowerType}
    }" />
</mvc:View>

方案2:跨多视图全局复用

如果需要在项目多个视图中复用同一个类型实例,可以将实例挂载到项目Component上:

  1. 在Component.js的init方法中创建全局实例:
sap.ui.define([
    "sap/ui/core/UIComponent",
    "mynamespace/model/type/Power"
], function(UIComponent, Power) {
    "use strict";

    return UIComponent.extend("mynamespace.Component", {
        init: function () {
            // 全局唯一实例,全项目可复用
            this._oGlobalPowerType = new Power({
                decimals: 0,
                emptyString: null
            });
            UIComponent.prototype.init.apply(this, arguments);
        }
    });
});
  1. 任意XML视图中通过$ownerComponent引用该实例:
<Input value="{
    path : 'model>power', 
    type : ${ownerComponent>/._oGlobalPowerType}
}" />

兼容低版本UI5方案(<1.69)

如果使用的UI5版本不支持$controller/$ownerComponent绑定语法,可以在控制器中定义返回类型实例的公共方法,XML中直接调用该方法即可:

// 控制器代码
getSharedPowerType: function() {
    if (!this._oSharedPowerType) {
        this._oSharedPowerType = new Power({
            decimals: 0,
            emptyString: null
        });
    }
    return this._oSharedPowerType;
}
<Input value="{
    path : 'model>powerA', 
    type : '.getSharedPowerType()'
}" />

内容的提问来源于stack exchange,提问作者Marvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:36:05