我怎样才能只获得模型本身的自定义属性?

How can I get only the properties that are custom attributes on the model itself?

我有一个自定义模型属性(类似于 ember-data 附带的属性)

var attr = function() {
    var value = '';
    return function(key, val) {
        if (arguments.length === 2) {
            value = val;
        }
        return value;
    }.property()
};

我用它来注释我的模型属性

var Foo = Ember.Object.extend({
    firstName: attr()
});

我正在寻找一种方法来获取 "only" 这些属性,当我在此实例上循环遍历 "keys" 时(示例 - 在我的回滚方法中,我想重置其中的每一个- 但不应重置其他键)

var Foo = Ember.Object.extend({
    firstName: attr(),
    rollback: function() {
        for(var key in this){
            this.set(key, "some value here");
        }
    }
});

是否可以通过某种方式使这个属性变得特殊,这样我就可以只遍历模型上的那些属性?

为什么不直接创建这些 'special' 属性的哈希值并对其进行迭代呢?

我想出了解决你问题的办法。在 attr() 方法中将 meta 添加到计算的 属性。它似乎是为这种情况设计的:

In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. (API Documentation)

所以,attr()方法:

var attr = function() {
  var value = '';
  return function(key, val) {
    if (arguments.length === 2) {
      value = val;
    }
    return value;
  }.property().meta({ isCustomAttr: true });
};

对象定义:

var Foo = Ember.Object.extend({
    firstName: attr(),
    rollback: function() {
      Foo.eachComputedProperty(function (item) {
        if(Foo.metaForProperty(item).isCustomAttr)         {
          console.log('This property was defined using custom attr() method and its key is: ' + item);
        }
      });
    }
});

Working demo. 输出:

"This property was defined using custom attr() method and its key is: firstName"

我相信这确实是 Ember 方式。