获取 ember 数据模型中任何 属性 的属性类型

Getting the attribute type of any property in an ember-data model

使用模型的特定实例,有没有办法获取任何给定属性的类型?例如,假设我有一个名为 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"}

工作,期望在我的辅助方法中,我不知道模型类型。我需要能够做这样的事情并拥有 return 相同的信息:

Ember.get(person, 'attributes');

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

person.getMetaInfoFor(property);

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

您可以使用 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

继续添加所有类型

Ember 2.4+, 使用 eachAttribute :

var attributeType

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