如何列出模型中定义的所有属性?
例如,如果我们有一个假想的博客应用程序的变体:
App.Post = DS.Model.extend({
title: DS.attr('string'),
text: DS.attr('string'),
comments: DS.hasMany('App.Comment')
});
然后,我正在寻找一种在没有应用程序实例的情况下迭代属性的可能性。Post模型:
# imaginary function
listAttributes(App.Post)
这样的函数可以生成一个数组,提供模型属性的名称和类型:
[{
attribute: "title",
type: "string"
},
{
attribute: "text",
type: "string"
}]
如何使用Ember实现这一点?
自2016年11月(Ember v2.9.0)起,实现这一点的最佳方法是使用eachAttribute
迭代器。
API参考=http://emberjs.com/api/data/classes/DS.Model.html#method_eachAttribute
modelObj.eachAttribute((name, meta) => {
console.log('key =' + name);
console.log('value =' + modelObj.get(name));
})
试试这个:
var attributes = Ember.get(App.Post, 'attributes');
// For an array of attribute objects:
var attrs = attributes.keys.toArray().map(function(key) {return attributes.get(key);} );
// To print the each attributes name and type:
attrs.forEach(function(attr) {console.log(attr.name, attr.type)});
当前Ember用户的更新
目前Ember.Map键和值是私有的,所以@Mike Grassotti的答案不再适用。
如果您不想使用私有对象,listAttributes
函数应该是这样的:
listAttributes(model) {
const attributes = Ember.get(App.Post, 'attributes'),
tempArr = [];
Ember.get(model.constructor, 'attributes').forEach( (meta, key) =>
temp.push({attribute: key, type: meta.type})
);
return tempArr;
}
* 请参阅commit Make Ember。将键和值映射为私有。