knockout observable array update不更新UI

时间:2014-04-03 09:09:46

标签: javascript user-interface knockout.js

当我更新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;时,它仍无效...任何帮助都将不胜感激...

Fiddle

1 个答案:

答案 0 :(得分:1)

问题在于数据绑定。

visible: !students().isDeleted

这会在observable数组中查找isDeleted属性。哪个不存在,所以它是假的,并且将始终显示所有元素。

如果你想隐藏学生,可见的绑定应该在<tr>

如果你想从可观察数组中删除学生,你可以删除它。

http://jsfiddle.net/8fALs/2/