2

我想用搜索到的数据更新我的数据绑定 Ul-Li 列表的内容。我正在使用以下 ViewModel

function PatientsModel(data)
{
    var self = this;

    self.Patients = ko.observableArray([]);

    self.Patients(data.Patients);

    self.addPatient = function (model, event)
    {
        alert("Patients to Add: " + model.LastName + ',' + model.FirstName);
        //Replace with AJAX Calls : self.people.push({ name: "New at " + new Date() });
    };

    self.removePatient = function (model, event)
    {
        alert("Patients to Delete:" + model.LastName + ',' + model.FirstName);
        //Replace with AJAX calls : self.people.remove(this);
    }

    self.RefreshData = function (data)
    {
        self.Patients = ko.observableArray([]);
        self.Patients(data.Patients);
    }
}

刷新我创建的 RefreshData 的内容,该方法将使用 Ul更新数据绑定 “foreach:患者”的患者

我正在做以下绑定:

AllPatientList.PatientsModel = null;
                            AllPatientList.PatientsModel = new PatientsModel(data);
                            ko.applyBindings(AllPatientList.PatientsModel, $('#AllPatientDiv>div>ul')[0]);

并遵循更新视图模型的内容:

if (AllPatientList.PatientsModel != null && AllPatientList.PatientsModel != undefined)
                            {
                                AllPatientList.PatientsModel.RefreshData(data);
                            }
                            else
                            {
                                AllPatientList.PatientsModel = new PatientsModel(data);
                                ko.applyBindings(AllPatientList.PatientsModel, $('#AllPatientDiv>div>ul')[0]);
                        }

但它不起作用,UL 的内容没有改变

此外,我尝试执行以下操作:

ko.cleanNode($('#AllPatientDiv>div>ul')[0]);
AllPatientList.PatientsModel = new PatientsModel(data);
                                ko.applyBindings(AllPatientList.PatientsModel, $('#AllPatientDiv>div>ul')[0]);

它正在生成带有重复/重复数据条目的列表。它显示 9 个列表项而不是 3 个。(每个重复 3 次)。

我无法弄清楚我在这里做错了什么。ko.cleanNode() 也不会从列表中删除内容。请帮助,我如何用更新的内容重新绑定 UL - LI 列表。

4

1 回答 1

2

它们没有改变,因为您的 RefreshData 函数正在破坏绑定。当您第一次调用时,会创建对数组applyBindings()的订阅。Patients当你打电话时,RefreshData你正在用一个新的数组覆盖数组。这个新数组没有绑定订阅。

如果要清除旧数组,请removeAll在添加新数据之前使用。这将保持绑定订阅完好无损。

编辑:

这是一个非常简单的小提琴演示这个

于 2012-10-30T19:06:13.847 回答