Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all attributes for a specific DS.Model in Ember.js

Tags:

ember.js

How can I list all the attributes defined in a model?

For example, if we have a variant for some imaginary blog application:

App.Post = DS.Model.extend({
    title: DS.attr('string'),
    text: DS.attr('string'),
    comments: DS.hasMany('App.Comment')
});

Then, I am looking for a possibility to iterate over the attributes without having an instance of the App.Post model:

# imaginary function
listAttributes(App.Post)

Such a function could yield an array providing name and type of the model attributes:

[{
    attribute: "title",
    type: "string"
},
{
    attribute: "text",
    type: "string"
}]

How to achieve that with Ember?

like image 463
Julius Avatar asked Jan 25 '26 04:01

Julius


1 Answers

As of Nov 2016 (Ember v2.9.0), the best way to approach this is to use the eachAttribute iterator.

API Reference = 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)); 
})
like image 163
Arnav Gupta Avatar answered Jan 26 '26 19:01

Arnav Gupta