【问题标题】:Getting the attribute type of any property in an ember-data model获取 ember-data 模型中任何属性的属性类型
【发布时间】:2015-04-12 13:07:38
【问题描述】:

使用模型的特定实例,有没有办法获取任何给定属性的类型?例如,假设我有一个名为 Person 的模型。在模板中,我将这个模型的一个实例和一个属性名称传递给一个辅助函数。在那个函数中,我希望能够找出它是什么类型的属性。

我看到的最接近的就是这个,直接来自 Ember 文档:

App.Person = DS.Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  birthday: attr('date')
});

var attributes = Ember.get(App.Person, 'attributes')

attributes.forEach(function(name, meta) {
  console.log(name, meta);
});

// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}

工作,希望在我的辅助方法中,我不知道模型类型。我需要能够做这样的事情并让它返回相同的信息:

Ember.get(person, 'attributes');

当然,我想做更多这样的事情:

person.getMetaInfoFor(property);

但目前这只是一厢情愿。我只是想弄清楚某些未知模型的某些未知属性是字符串还是日期。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

    Ember 2.4+,使用eachAttribute

    var attributeType
    
    person.eachAttribute(function(name, meta){
        if (name === property){
            attributeType = meta.type
        }
    })
    

    【讨论】:

      【解决方案2】:

      你可以使用 JQuery type() 函数获取属性的类型

      function getMetaInfoFor(input){
        if(jQuery.type( input) === "boolean"){
          return boolean;
         }
       if(jQuery.type( input) === "number"{
         return number;
        }
      if(jQuery.type(input) === "date"){
         return date;
        }
      };
      

      您需要编写一个函数来根据您的要求将输入日期转换为自定义格式。

      您可以按照link继续添加所有类型

      【讨论】:

      • 这会起作用,除了日期之类的东西,它们存储为日期时间字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 2017-07-27
      • 2013-06-03
      • 1970-01-01
      • 2014-01-07
      • 2019-09-28
      相关资源
      最近更新 更多