简体   繁体   中英

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.

you can get the type of an property by using JQuery type() function

function getMetaInfoFor(input){
  if(jQuery.type( input) === "boolean"){
    return boolean;
   }
 if(jQuery.type( input) === "number"{
   return number;
  }
if(jQuery.type(input) === "date"){
   return date;
  }
};

you will need to write a function to convert you input date in custom format as per your requirement.

you can keep adding all types as per this link

Ember 2.4+, use eachAttribute :

var attributeType

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM