繁体   English   中英

灰烬计算的属性缓慢且不一致

[英]Ember Computed Property Slow and Inconsistent

我有一个显示视频并允许用户对视频进行评分的应用。 视频下方会显示平均评分和对视频进行评分的次数。 为了计算这些,我向每个模型添加了计算属性。 平均属性依赖于求和和长度计算的属性。

/*global Ember */
import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  url: DS.attr('string'),
  ratings: DS.hasMany('userrating'),
  users: DS.hasMany('user'),
  rated: DS.attr('boolean'),

  // maps through ratings objects and pulls out the rating property
  // returns an array of integers that represent all of one videos ratings
  numRatings: Ember.computed.mapBy('ratings', 'rating'),

  // returns the sum of a videos ratings
  sum: Ember.computed.sum('numRatings'),

  // returns the number of ratings a video has
  length: Ember.computed('numRatings', function () {
    return this.get('numRatings').length;
  }),

  // returns true if the video has only been rated once
  // this is used to determine if '1 user' or '2 users' etc.
  // should be displayed
  one: Ember.computed('length', function () {
    if (this.get('length') === 1) {
      return true;
    }
  }),

  // returns the average rating of a video
  avg: Ember.computed('length', 'sum', function () {
    return Math.round(this.get('sum') / this.get('length'));
  })
});

我注意到有时会显示总和而不是平均值。 这通常只发生一秒钟,然后平均值会正确显示,但偶尔会不显示平均值。 今天,除一个视频外,所有视频均正确显示,但其中一个视频的平均评分为“ 33/5”。

为什么会这样呢? 我是否应该构建Ember计算的属性以相互依赖? 这仅仅是浏览器运行缓慢的问题吗? 我正在加载一堆视频和图像。

总的来说,我对Web开发还很陌生,这是我的第一个Ember应用。

谢谢!

在不了解整个体系结构的情况下很难真正知道哪里可能存在性能问题,但是我可以看到以下内容:

  • 您与与video模型相关联的user userratinguser模型有关系
  • 您的sumlength计算属性都基于另一个计算值,另一个计算值本身正在执行map以将rating值从ratings对象中拉出
  • 您还有另一个计算出的观看length ,它纯粹是确定代码中其他位置的“用户”一词的复数形式
  • 最后,您有一个avg计算的avg ,它也在监视其他两个已计算的属性

现在,我仍然不能真正提供一个确切的答案,但是这里有一些建议可以减轻(也许)减轻您的模型负担。

  1. 完全消除one计算。 如果您确实想知道是否选择了一个,则可以在组件/控制器端执行此计算,但是可以执行其他操作,例如Ember.computed.equal('numRatings', 1)
  2. 可以通过使用this.get('numRatings.length')来消除length属性
  3. avgnumRatings以便仅在该特定数字更改时才重新计算,因为您已经知道sum也会更新,因此也可能会减少观察到的属性的数量

就是说,如果它仍然表现不佳,则可能要确保在用户userrating条目中找到的数据正确。 如果仍然感到缓慢或需要花费时间,还可以尝试将mapBy更改为普通的JS for loop循环,因为它们比使用Array方法要快得多(尽管可读性较差)。

祝好运!

length: Ember.computed('numRatings',需要是length: Ember.computed('numRatings.[]', --您需要观察数组的长度,而不是数组本身的长度(仅在出现以下情况时才会引发标志)值整体上会发生变化),您也可以使用alias属性-Ember.computed.alias('numRatings.length')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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