在Ember.js中列出特定DS.Model的所有属性

在Ember.js中列出特定DS.Model的所有属性,ember.js,Ember.js,如何列出模型中定义的所有属性 例如,如果我们有一个虚拟博客应用程序的变体: App.Post = DS.Model.extend({ title: DS.attr('string'), text: DS.attr('string'), comments: DS.hasMany('App.Comment') }); 然后,我正在寻找一种在没有App.Post模型实例的情况下迭代属性的可能性: # imaginary function listAttributes(App.

如何列出模型中定义的所有属性

例如,如果我们有一个虚拟博客应用程序的变体:

App.Post = DS.Model.extend({
    title: DS.attr('string'),
    text: DS.attr('string'),
    comments: DS.hasMany('App.Comment')
});
然后,我正在寻找一种在没有App.Post模型实例的情况下迭代属性的可能性:

# imaginary function
listAttributes(App.Post)
这样的函数可以生成一个数组,提供模型属性的名称和类型:

[{
    attribute: "title",
    type: "string"
},
{
    attribute: "text",
    type: "string"
}]
如何使用余烬实现这一点?

试试以下方法:

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.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;
}
*请参见提交。

自2016年11月起(Ember v2.9.0),实现此目的的最佳方法是使用
eachAttribute
迭代器

API参考=

modelObj.eachAttribute((name, meta) => {
    console.log('key =' + name);
    console.log('value =' + modelObj.get(name)); 
})