我想用搜索到的数据更新我的数据绑定(bind) 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进行数据绑定(bind)“foreach:患者”
我正在执行以下绑定(bind):
AllPatientList.PatientsModel = null;
AllPatientList.PatientsModel = new PatientsModel(data);
ko.applyBindings(AllPatientList.PatientsModel, $('#AllPatientDiv>div>ul')[0]);
并按照以下步骤更新 View 模型的内容:
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() 也不会从列表中删除内容。请帮助,我如何用更新的内容重新绑定(bind) UL - LI 列表。
最佳答案
它们没有改变,因为您的 RefreshData 函数破坏了绑定(bind)。当您第一次调用 applyBindings()
时,会创建对 Patients
数组的订阅。当您调用 RefreshData
时,您将用新数组覆盖该数组。这个新数组没有绑定(bind)订阅。
如果要清除旧数组,请在添加新数据之前使用removeAll
。这将使绑定(bind)订阅保持完整。
编辑:
这是一个very simple fiddle证明这一点
关于jquery - ko.applyBinding 使用 Knockout 刷新搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13145921/