【问题标题】:How to get the data object from a single record in the model?如何从模型中的单个记录中获取数据对象?
【发布时间】:2018-04-23 23:25:43
【问题描述】:

最近这成为了我的应用程序中的一个错误,虽然我不知道发生了什么变化(我还没有升级 Ember 的版本,它仍然是 1.13)。我需要了解的是如何以常规方式访问模型上单个记录的对象。

我有以下代码根据其他两个属性过滤我的model

  recordsBySelectedShapeAndColor = get(this, "model").filter(function(rec) {
    //filter the model by the chosen shape and color
    return (
      get(rec, "shape") === theShape &&
      get(rec, "color") === theColor
    );
  });

然后我需要创建这些过滤记录的摘要,我正在使用 reduce(),但如果该过滤器只返回一条记录,那么 reduce 不会返回正确的结果,所以我有以下条件:

if (recordsBySelectedShapeAndColor.length < 2) {
  summary = recordsBySelectedShapeAndColor[0]._data;
} else {
  summary = recordsBySelectedShapeAndColor.reduce(function(a, b) {
...
}

if 中的行不再返回简单对象,因此我将其更改为 summary = recordsBySelectedShapeAndColor[0]._internalModel._data; 并且它可以工作,但它看起来很可疑(._data 总是这样做)。访问带下划线的属性是代码气味吗?如果是这样,我怎样才能只从模型上的那条记录中获取数据?

【问题讨论】:

    标签: ember.js model


    【解决方案1】:

    使用get(recordsBySelectedShapeAndColor, 'firstObject')

    【讨论】:

    • 天啊,就这些吗??我试过recordsBySelectedShapeAndColor.firstObject 并没有得到任何结果,因为它返回了一个我看不到数据对象的类,所以我想我还没有到那里。谢谢!!!这也有效,不确定哪个更好用:recordsBySelectedShapeAndColor.get("firstObject")
    • 在 ember 中始终使用.get!这不是真正的Array,而是Ember Enumerable
    • 谢谢@Lux。从这个 (stackoverflow.com/questions/40606827/…) 看来,如果您不知道您的对象是否是 Ember 对象,Ember.get() 似乎比this.get() 有一个很好的用例,因为get() 将继续工作,而this.get()如果不是 Ember 对象,将失败。
    猜你喜欢
    • 2021-02-14
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多