获取Knockout.js中强类型可观察项目数组中的项目总数

时间:2016-10-26 12:24:32

标签: jquery model-view-controller knockout.js

我需要有关如何在视图中显示可观察数组集合的总长度的帮助。无论何时我尝试,结果总是为零。以下是样本。 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);
        }

    });

    //Get total of array collection
    tHour = self.courses().length;
    // button functions
    removeCourse = function (course) { self.courses.remove(course); }


}

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

这是我的观点

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

问题是tHour返回0而不是数组的期望长度。

1 个答案:

答案 0 :(得分:2)

两个选项:

  1. 使用courses().length

    <td data-bind="text: courses().length"></td>
    
  2. 使用计算:

    self.tHour = ko.pureComputed(function() {
        return self.courses().length;
    });
    
  3. 旁注:您的模板无效。您不能Total CH直接在tr内(例如,不在tdth内)。

    旁注2:您的tHourimplicit global; 1 ,您的意思是self.tHour = ...

    1 这是我贫穷的小博客上的帖子。