当我更新Knockout的observable
元素时,UI没有获得更新
HTML
<tbody data-bind="foreach: students, visible: !students().isDeleted">
<tr>
<td data-bind="text: RollNo"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Phone"></td>
<td data-bind="text: Email"></td>
<td>
<a href="#" data-bind="click: $root.editStudent">Edit</a>
<a href="#" data-bind="click: $root.deleteStudent">Delete</a>
</td>
</tr>
</tbody>
的Javascript
function StudentModel(student){
this.RollNo = ko.observable(student.RollNo);
this.Name = ko.observable(student.Name);
this.Phone = ko.observable(student.Phone);
this.Email = ko.observable(student.Email);
this.isDeleted = ko.observable(student.isDeleted);
this.isEdited = ko.observable(student.isEdited);
}
function StudentViewModel() {
//Array of students
this.students = ko.observableArray();
//Data retrived from the server
var listStudent= JSON.parse(@Html.Raw(ViewBag.StudentsList));;
var mappedStudents = $.map(listStudent, function(student) { return new StudentModel(student) });
//Map it to show the data
this.students(mappedStudents);
//Delete student
this.deleteStudent= function(student){
var stu = this.students()[this.students.indexOf(student)];
stu.isDeleted(true);
}.bind(this);
当我点击Delete
时,用户界面未更新...当我尝试stu.isDeleted=true;
时,它仍无效...任何帮助都将不胜感激...
答案 0 :(得分:1)
问题在于数据绑定。
visible: !students().isDeleted
这会在observable数组中查找isDeleted
属性。哪个不存在,所以它是假的,并且将始终显示所有元素。
如果你想隐藏学生,可见的绑定应该在<tr>
。
如果你想从可观察数组中删除学生,你可以删除它。