如何检索Ember.js模型的所有属性

时间:2013-03-27 12:09:03

标签: javascript ember.js

我正在使用Ember.js中的表单,我想检索所有模型属性的列表,以便我可以在不同时刻拍摄表单状态的快照。有没有办法获得模型的所有属性列表?

例如,如果我的模型是:

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'),
}

然后我想有这样的事情:

> getEmberProps('User')

["name", "email", "current_password", "password", "password_confirmation", "admin"]

5 个答案:

答案 0 :(得分:16)

您可以在模型上使用toJSON方法,并从对象中获取密钥。

Ember.keys(model.toJSON())

请注意,不会返回关系密钥。

答案 1 :(得分:4)

打印字段及其值的简便方法:

Ember.keys(model.toJSON()).forEach(function(prop) { console.log(prop + " " + model.get(prop)); } )

答案 2 :(得分:4)

你也可以用这个:
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; });

也有类似的关系属性。

答案 3 :(得分:0)

没有简单的方法,但您可以尝试这样的自定义mixin:

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
    }
});

你可以像这样使用它:

App.YourObject = Ember.Object.extend(Ember.AllKeysMixin, {
 ... //your stuff
});
var yourObject = App.YourObject.create({
  foo : "fooValue";
});
var keys = yourObject.getKeys(); // should be ["foo"];

答案 4 :(得分:0)

在2018年:使用Ember Data的eachAttribute

因此,给定模型Foo:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
    "name": attr('string'),
    "status": attr('string')
});

让我们通过构造函数获取模型的定义:

var record = this.store.createRecord('foo', {
    name: "model1",
    status: "status1"
});
this.modelClass = record.constructor;

并为其每个Ember Data属性调用一个函数:

modelClass.eachAttribute(function(key, meta){ 
   //meta provides useful information about the attribute type
}
相关问题