Search code examples
javascriptember.jsember-data

Getting the attribute type of any property in an ember-data model


Using a specific instance of a model, is there any way to get the type of any given attribute? For example, say I've got a model called Person. Inside a template, I pass an instance of this model and a property name to a helper function. In that function, I want to be able to find out what type of property that is.

The closest thing I've seen is this, straight from the Ember docs:

App.Person = DS.Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  birthday: attr('date')
});

var attributes = Ember.get(App.Person, 'attributes')

attributes.forEach(function(name, meta) {
  console.log(name, meta);
});

// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}

This would work, expect that in my helper method, I don't know the model type. I need to be able to do something like this and have it return the same information:

Ember.get(person, 'attributes');

Sure, I'd like to do something more like this:

person.getMetaInfoFor(property);

But that's just wishful thinking at this point. I'm just trying to figure out if some unknown property of some unknown model is a string or a date. Any help would be greatly appreciated.


Solution

  • Ember 2.4+, use eachAttribute :

    var attributeType
    
    person.eachAttribute(function(name, meta){
        if (name === property){
            attributeType = meta.type
        }
    })