显示可观察数组集合中类型化项的总和

本文关键字:类型化 观察 数组 集合 显示 | 更新日期: 2023-09-27 18:15:26

请我需要帮助如何在一个可观察数组中显示一个类型化项目的总和。每当我尝试,返回的结果总是NaN。下面是样本。MyVM.js文件:

//Model
var Course = function (data) {
    var self = this;
    self.title = ko.observable(data.Title);
    self.creditHour = ko.observable(data.CreditHour);
self.result = ko.observableArray(data.result);
    return self;
}
//View Model
var CourseList = function () {
    var self = this;
    self.courses = ko.observableArray([]);
    $.ajax({
        type: "GET",
        url: '/Student/Register_For_Courses',
        contentType: "application/json; charset=utf-8",
        datatype: 'json',
        traditional: true,
        success: function (data) {
            ko.utils.arrayForEach(data, function (data) {
                self.courses.push(new Course(data))          
            });
        },
        error: function (err) {
            alert(err.status + " : " + err.statusText);
        }
    });
    self.tHour = ko.pureComputed(function () {
    var total = 0;
    var count=self.courses().length;
    for (var i = 0; i <count ;i++)
    {
        var course =  Course(self.courses()[i]);
        total += parseInt(course.creditHour(),10);
    }
    return total;
});
    // button functions
    self.removeCourse = function (course) { self.courses.remove(course); }

}
$(document).ready(function () {
    ko.applyBindings(new CourseList());
});

这是我的视图

<tr>
   Total CH<td data-bind="text:tHour"></td>
</tr>

返回值为NaN

显示可观察数组集合中类型化项的总和

这样怎么样?https://jsfiddle.net/othkss9s/19/

我使用了删除实用程序arrayForEach将它们相加http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html

我不能做你的ajax调用,所以我只是硬编码数据,但它应该代表你从ajax调用返回。代码如下:

var Data = [{
  title: "English",
  creditHour: 3.23,
  result: "A"
}, {
  title: "Gym",
  creditHour: 1.04,
  result: "A"
}, {
  title: "AP Calc",
  creditHour: 4.34,
  result: "B"
}, ]
function course(data) {
  this.title = ko.observable(data.title);
  this.creditHour = ko.observable(data.creditHour);
  this.result = ko.observable(data.result);
}
function model() {
  var self = this;
  this.courses = ko.observableArray("");
  this.totalCreditHours = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.courses(), function(item) {
      var value = parseFloat(item.creditHour());
      if (!isNaN(value)) {
        total += value;
      }
    });
    return total.toFixed(2);
  }, this);
};
var myViewModel = new model();
$(document).ready(function() {
  ko.applyBindings(myViewModel);
  $.each(Data, function(idx, obj) {
    myViewModel.courses.push(
      new course(obj)
    );
  });
});