3

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

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

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"
}]

如何使用 Ember 实现这一目标?

4

3 回答 3

6

截至 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)); 
})
于 2016-11-07T02:32:00.300 回答
4

试试这个:

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)});
于 2013-07-08T18:02:49.440 回答
0

当前 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;
}

* 请参阅提交将 Ember.Map 键和值设为私有

于 2016-10-28T09:29:38.190 回答