Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve all properties of an Ember.js model

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"]
like image 417
joscas Avatar asked Mar 27 '13 12:03

joscas


People also ask

What are computed properties in Ember?

What are Computed Properties? In a nutshell, computed properties let you declare functions as properties. You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property. You can then use it the same way you would any normal, static property.

What is model in Ember JS?

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.

How does Ember JS work?

Ember uses templates to organize the layout of HTML in an application. Ember templates use the syntax of Handlebars templates. Anything that is valid Handlebars syntax is valid Ember syntax. Here, {{name}} is a property provided by the template's context.


2 Answers

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.

like image 98
piotrze Avatar answered Sep 22 '22 06:09

piotrze


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.

like image 26
Michael Avatar answered Sep 26 '22 06:09

Michael