gpt4 book ai didi

sapui5 - 创建自定义枚举类型

转载 作者:行者123 更新时间:2023-12-01 19:27:52 25 4
gpt4 key购买 nike

我想为自定义控件创建一个自定义枚举类型,例如 https://sapui5.hana.ondemand.com/docs/api/symbols/sap.ui.core.ValueState.html#.Error .

我的问题是:

  • 如何创建枚举类型?
  • 在自定义控件上,您只能传递属性枚举
    类型。如何验证给定的枚举是否有效?

最佳答案

这是一个示例:https://embed.plnkr.co/DhtkXOkMi12D1AYK

为了在 UI5 中创建枚举类型,需要考虑某些规则:

  • 枚举定义必须是普通对象。在内部,它通过 sap/base/util/isPlainObject 进行验证.
  • 每个键值对必须彼此相同
  • 不支持重命名。
  • 只有字符串类型的键和值是支持。
{
Red: "Red",
Blue: "Blue",
Yellow: "Yellow"
}

为了实际使用枚举对象:

  1. 枚举对象必须首先是全局可访问的。一种方法是定义一个由普通对象组成的模块,并使其在模块名称下可用。例如:

    /**
    * file: MyColor.js
    * path: "custom/control/type/"
    * namespace: "demo"
    */
    sap.ui.define({ // module value
    Red: "Red",
    Blue: "Blue",
    Yellow: "Yellow",
    }, true); // resulting module name: "demo.custom.control.type.MyColor"
  2. 对象的模块名称必须分配给属性定义中的类型:

    sap.ui.define([
    "sap/ui/core/Control",
    "./type/MyColor", // allows the enum definition to be stored in the type registry
    "./MyColorBoxRenderer", // prevents fetching renderer via sync XHR
    ], function (Control) {
    "use strict";

    return Control.extend("demo.custom.control.MyColorBox", {
    metadata: {
    properties: {
    "selectedColor": {
    type: "demo.custom.control.type.MyColor"
    },
    },
    },
    // ...
    });
    });

在上面的示例中,selectedColor 属性仅等待 "Red""Blue""Yellow “。让我们测试一下:

  • new MyColorBox().getMetadata().getProperty("selectedColor").getType().isEnumType() 返回 true (ManagedObject) > 动态创建 sap.ui.base.DataType 对象)✔️
  • new MyColorBox().setSelectedColor("Hans") 按预期抛出错误:

    "Hans" is of type string, expected demo.custom.control.type.MyColor for property "selectedColor" of Element [...]. ✔️

  • new MyColorBox().setSelectedColor("Yellow") 成功存储值 ✔️
<小时/>

注意

不要不要尝试通过DataType.create创建枚举类型。

Array types and enumeration types cannot be created with this method. They're created on-the-fly by DataType.getType when such a type is looked up. (Source)

引用文献

关于sapui5 - 创建自定义枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41983723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com