knockout.js 当与knockout js一起使用时,引导模型未正确关闭

hsvhsicv  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(98)

我正在使用knockout和bootstrap js。
我的要求:

  • 我正在创建一个HTML表单,并且已经使用knockout完成了数据绑定。
  • 提交此表单后,我将以引导模式向用户显示一条消息。
  • 在关闭这个模态时,我需要重置HTML表单。因此,在单击关闭按钮时,我执行了一个单击绑定并调用了一个方法。下面是该方法的代码片段。
// Re-setting the observable  to default value
me.addStudentForClass(null);
me.parents=ko.mapping.fromJS(new parentInfoModel(undefined));
me.localGuardian=ko.mapping.fromJS(new localGuardian(undefined));
me.lastSchoolEducation=ko.mapping.fromJS(new lastSchoolEducation(undefined));
// Closing bootstrap Modal
$('modal-id').modal('hide');
// Cleaning the knockout node , to reflect the reset change 
ko.cleanNode($('#add-student')[0]);
// and binding the view model 
ko.applyBindings(app.mainViewModel, $('#add-student')[0]);

如果我们没有使用下面的两行代码,那么模态工作正常,模态在单击关闭按钮时关闭

ko.cleanNode($('#add-student')[0]);
ko.applyBindings(app.mainViewModel, $('#add-student')[0]);

但是我需要使用上面的两行代码,因为它需要重新设置我的表单。
如果我们延迟清理节点,则它工作正常。

function saysomething(){
			ko.cleanNode($('#add-student')[0]);
			ko.applyBindings(app.mainViewModel, $('#add-student')[0]);
     }
     setTimeout(saysomething, 500);	}

请帮助我解决这个问题。我不想使用setTimeout。请建议最佳实践。
谢谢您

clj7thdc

clj7thdc1#

您可以侦听hidden事件,而不是使用setTimeout

$('#modal-id').on('hidden.bs.modal', function (e) {
  ko.cleanNode($('#add-student')[0]);
  ko.applyBindings(app.mainViewModel, $('#add-student')[0]);
})

有关处理模式事件的信息,请参见Bootstrap的文档。

相关问题