gpt4 book ai didi

javascript - knockout 数组内的对象数组

转载 作者:行者123 更新时间:2023-11-28 08:56:58 25 4
gpt4 key购买 nike

我不太了解 knockout ,但我正在投入其中。问题:我正在尝试检索对象列表(数组)内的对象列表(数组)。

示例:(只是为了使其变得非常简单)

老师 -> 学生

  1. 老师 #1

    • 学生1
    • 学生2
    • 学生3
  2. 老师#2

    • 学生1
    • 学生2
    • 学生3
  3. 老师#3

    • 学生1
    • 学生2
    • 学生3

到目前为止,我能够显示所有教师的列表,但是当显示学生列表时,最后一个节点(教师#3)显示教师(#1和#2和#3)的所有学生;教师 #1、#2 为空。

var ViewModel = {
Teachers: ko.observableArray([])
}

function LoadTeachers(....) //Here Teacher list is loaded successfully.>

ko.applyBindings(ViewModel);


function teacher(T){
this.TeacherID:ko.observable(T.TeacherID);
this.TeacherName: ko.observable(T.TeacherName);

this.StudentArray = ko.observableArray([]);

function student(s){
this.StudentID=ko.observable(s.StudentID);
this.Name = ko.observable(s.s.Name);
}

$.getJson('...'); // here is where Student array is loaded.

}

然后我会在我的 View 页面中:

foreach: Teacher  
foreach: Student

我只是用我的 C# 知识来申请 knockout 。我认为问题在于在教师对象内声明学生数组。因为学生对于每个老师来说都是一个 child 。这就是我在 C# 中所做的。

有谁知道这个编码是否可行?希望是这样!

提前致谢

最佳答案

我暂时忽略了 Knockout 映射插件(它很好,但写得不是很好)。原因是为了让你简单地看到解决方案。所以你有一些 knockout 的怪事,但大多数都是你犯了一个关闭错误。代码中最重要的部分是 var newTeacher = ...。这很重要,因为您需要在嵌套的 ajax 闭包中使用它。这是代码和工作 fiddle 的链接:

$(document).ready(function(){
var ViewModel = {
Teachers: ko.observableArray([])
};

// some fake data to use instead of the ajax calls below, just so it works in fiddle
var fakeTeacherData = [{TeacherID: 1, TeacherName: 'Dan'}, {TeacherID: 2, TeacherName: 'Marian'}];
var fakeStudentData = [{StudentID: 1, Name: 'Student 1'}, {StudentID: 2, Name: 'Student 2'}];

$.get('/echo/json', function(teacherData){
// here you would use the data passed in of course
ko.utils.arrayForEach(fakeTeacherData, function(T){
var newTeacher = new teacher(T);
ViewModel.Teachers.push(newTeacher);

$.get('/echo/json', function(studentData){
// here you would use the data passed in of course
ko.utils.arrayForEach(fakeStudentData, function(S){
newTeacher.Students.push(new student(S));
});
});
});
});
ko.applyBindings(ViewModel);
});

function teacher(T){
this.TeacherID = ko.observable(T.TeacherID);
this.TeacherName = ko.observable(T.TeacherName);
this.Students = ko.observableArray([]);
}

function student(S){
this.StudentID = ko.observable(S.StudentID);
this.Name = ko.observable(S.Name);
}

http://jsfiddle.net/kXQxA/

关于javascript - knockout 数组内的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com