Reputation: 7674
I'm working with forms in Ember.js and I want to retrieve a list of all model properties so that I can take snapshots of the state of the form at different moments. Is there a way to get a list of all properties of a model?
For example, if my model is:
App.User = DS.Model.extend({
name: DS.attr('string'),
email: DS.attr('string'),
current_password: DS.attr('string'),
password: DS.attr('string'),
password_confirmation: DS.attr('string'),
admin: DS.attr('boolean'),
}
Then I would like to have something like this:
> getEmberProps('User')
["name", "email", "current_password", "password", "password_confirmation", "admin"]
Upvotes: 11
Views: 15439
Reputation: 8724
in 2018: use Ember Data's eachAttribute.
So, given a model Foo:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
"name": attr('string'),
"status": attr('string')
});
Let's get the model's definition via the constructor:
var record = this.store.createRecord('foo', {
name: "model1",
status: "status1"
});
this.modelClass = record.constructor;
and invoke a function for each of its Ember Data attributes:
modelClass.eachAttribute(function(key, meta){
//meta provides useful information about the attribute type
}
Upvotes: 0
Reputation: 489
You can simply use toJSON method on model and get the keys from object.
Ember.keys(model.toJSON())
Note that will not return you keys for relations.
Upvotes: 20
Reputation: 12011
You can also use this:
http://emberjs.com/api/data/classes/DS.Model.html#property_attributes
http://emberjs.com/api/data/classes/DS.Model.html#method_eachAttribute
Ember.get(App.User, 'attributes').map(function(name) { return name; });
Ember.get(userInstance.constructor, 'attributes').map(function(name) { return name; });
There's also similar properties for relationships too.
Upvotes: 7
Reputation: 301
An easy way to print out the fields and their values:
Ember.keys(model.toJSON()).forEach(function(prop) { console.log(prop + " " + model.get(prop)); } )
Upvotes: 4
Reputation: 11668
There is no easy way, but you could try a custom mixin like this:
Ember.AllKeysMixin = Ember.Mixin.create({
getKeys: function() {
var v, ret = [];
for (var key in this) {
if (this.hasOwnProperty(key)) {
v = this[key];
if (v === 'toString') {
continue;
} // ignore useless items
if (Ember.typeOf(v) === 'function') {
continue;
}
ret.push(key);
}
}
return ret
}
});
You can use it like this:
App.YourObject = Ember.Object.extend(Ember.AllKeysMixin, {
... //your stuff
});
var yourObject = App.YourObject.create({
foo : "fooValue";
});
var keys = yourObject.getKeys(); // should be ["foo"];
Upvotes: 0