I found some similar examples to what I'm trying to do in Access viewModel in javascript function outside viewModel's scope, but have not been able to figure out what to do in my particular case. I have several teachers, show their salaries, along with total salaries, but want to show the relative percentage of their salary as it relates to the total. Here's my view:
<table>
<tr>
<th></th>
<th>Salary</th>
<th>Salary Percent</th>
</tr>
<tbody data-bind="foreach: teachers">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: salary"></td>
<td data-bind="text: salaryPercent"></td>
</tr>
</tbody>
<tr>
<td>Total Salary</td>
<td data-bind="text: totalSalary"></td>
</tr>
</table>
view model:
var Teacher = function(id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
this.salaryPercent = ko.computed(function() {
// return accounting.toFixed((this.salary/178000)*100, 0) + '%'; // works with hard-coded total salary
return accounting.toFixed((this.salary/viewModel.totalSalary)*100, 0) + '%';
// return this.salary; // works, returns the same salary as this.salary above
}, this);
};
var viewModel = function(teachers) {
var self = this;
self.teachers = ko.observableArray(teachers);
self.totalSalary = ko.computed(function() {
var total = 0;
ko.utils.arrayForEach(self.teachers(), function(teacher) { total += teacher.salary; });
return total;
});
};
var initialTeachers = [
new Teacher(1, "Tom", 40000),
new Teacher(2, "Betty", 41000),
new Teacher(3, "Charles", 45000),
new Teacher(4, "Daniel", 52000)
];
var vm = new viewModel(initialTeachers);
ko.applyBindings(vm);
and css:
td, th {
border: solid 1px black;
padding: 2px;
}
TIA, Steve
Note: I'm using the accounting.js library, included with jsfiddle.