10

我正在使用 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"]
4

5 回答 5

18

您可以简单地在模型上使用toJSON方法并从对象中获取键。

Ember.keys(model.toJSON())

请注意,这不会返回您的关系键。

于 2014-08-05T08:26:45.217 回答
6

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

关系也有类似的属性。

于 2015-04-10T06:54:12.977 回答
4

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

Ember.keys(model.toJSON()).forEach(function(prop) { console.log(prop + " " + model.get(prop)); } )
于 2015-01-23T18:39:10.997 回答
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"];
于 2013-03-27T12:46:05.180 回答
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
}
于 2018-11-12T11:02:42.267 回答