【问题标题】:Dynamically define properties to Ember Data model动态定义 Ember 数据模型的属性
【发布时间】:2017-08-20 05:50:59
【问题描述】:

我正在开发一个数据模型,该模型具有一组始终存在的预定义属性,以及用户为其定义的其他自定义属性。

一家公司有很多角色。除了所有角色在不同公司中具有的一组固定属性之外,使用此系统的每个公司都希望为其所有角色定义自定义属性。

我们的想法是,json-api 中的角色有效负载带有所有属性,无论是否自定义:

{
  "id": "123",
  "type": "roles",
  "attributes": {
    "name": "CEO",
    "salary": 100000,
    "favoriteColor": "blue"
  }
}

在上述角色中,namesalary 是默认属性,存在于所有角色中,与公司无关,但 favoriteColor 是拥有此角色的特定公司定义为他们需要拥有的自定义属性它的所有角色。

考虑到我无法在角色模型定义中定义这些自定义属性,我想知道是否可以使用 Ember Data 来解决这样的问题:

// app/models/role.js
export default DS.Model.extend({
  name: DS.attr('string'),
  salary: DS.attr('number'),
})

更糟糕的是,这些自定义属性不一定是字符串值,但也可以指定它们的类型。因此,公司可能希望拥有string 类型的favoriteColor,以及date 类型的birthDate

【问题讨论】:

    标签: javascript json ember.js ember-data json-api


    【解决方案1】:

    我会添加一个属性(您的服务器需要在config 属性中返回附加参数):

    // app/models/role.js
    export default DS.Model.extend({
      name: DS.attr('string'),
      salary: DS.attr('number'),
      config: DS.attr() // accepts anything, including json
    })
    

    选项 1: 通过自定义序列化程序的 normalize 函数处理序列化到属性中,这会将来自 config 的值推送到序列化属性中。像这样的:

    // serializers/role.js
    export default <Your Base Serializer>.extend({
            normalize(typeClass, hash) {
                const result = this._super(typeClass, hash);
    
                result.data.attributes =  Object.keys(data.attributes.config).reduce((acc, value) => {
                    acc[value] = result.data.attributes.config[value];
                    return acc
                }, result.data.attributes);
    
                return result;
            },
        });
    

    选项2(如果您的选择有限):使用计算函数alias

    // app/models/role.js
    export default DS.Model.extend({
      name: DS.attr('string'),
      salary: DS.attr('number'),
      config: DS.attr(), // accepts anything, including json
    
      favoriteColor: Ember.computed.alias('config.favoriteColor')
    })
    

    【讨论】:

      【解决方案2】:

      使用可自定义的jsona 数据格式化程序,它可能对自动创建 ember 数据模型很有帮助。此外,还可以自动从您的 ember 数据模型创建正确的 JSON :)

      【讨论】:

        猜你喜欢
        • 2015-12-01
        • 1970-01-01
        • 2014-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多