Take a look at this first:
This is Knckoutjs + Jquery Raty Plugin
Assume these are columns from a database:
story_rev: ko.observable(),
animation_rev: ko.obervable(),
sound_rev: ko.observable(),
characters_rev: ko.observable(),
enjoyment_rev: ko.observeable(),
These are basically rating based events in the database which ranges from 0-5 with a step of 0.5 (number input)
Does anyone know how to make it so that it calculates the average of the 5 ratings? I kinda know how to do it via jquery, but knockoutjs is a different story for me.
You could use a computed observable to calculate the average.
function AppViewModel() {
var self = this;
self.story_rev = ko.observable();
self.animation_rev = ko.observable();
self.sound_rev = ko.observable();
self.characters_rev = ko.observable();
self.enjoyment_rev = ko.observable();
self.averageRating = ko.computed(function() {
var ratings = [self.story_rev(), self.animation_rev(), self.sound_rev(), self.characters_rev(), self.enjoyment_rev()];
return ratings.reduce(function(a, b) {
return a + parseInt(b, 10);
}) / ratings.length;
});
}
var model = new AppViewModel();
model.story_rev(1);
model.animation_rev(2);
model.sound_rev(3);
model.characters_rev(4);
model.enjoyment_rev(5);
//Should output the average (in this case 3)
console.log(model.averageRating());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>