I have an app that displays videos and allows users to rate the videos. An average rating and the number of times the video has been rated are displayed beneath it. To calculate these I have added computed properties to each model. The average property relies on the sum and length computed properties.
/*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'));
})
});
I have noticed that sometimes the sum is displayed in place of the average. This usually happens only for a second and then the average correctly displays, but every once in a while the average does not display. Today, all videos except for one were displaying correctly, but that one video was displaying ’33/5’ as the average rating.
Why is this happening? Should I not build Ember computed properties to rely on each other? Is this just a problem with the browser being slow? I am loading a bunch of videos and images.
I am pretty new to web development in general and this is my first Ember app.
Thanks!
length: computed.readOnly('numRatings.length')
,one: computed.equal('length', 1)
– nem035