我有一个我在ajax应用程序中创建的视图模型 . 当我渲染我的第一段html时,会调用ko.applyBindings() . 后来我做了第二次ajax调用来渲染html的另一部分并绑定到同一个视图模型 . 但是,因为当我第一次调用ko.applyBindings()时,第二个ajax中的html元素不存在,那么当我的第二个html部分被检索时,data-bind不起作用 .
这是一个非常简单的示例,其中第一个复选框正确绑定 . 然后content2将通过后续的ajax调用加载,并且复选框无法绑定
<div id='container'>
<div id="content1"> <span>Opt In</span>
<input data-val-required="field is required." id="cbOptIn" name="OptIn" type="checkbox" data-bind="checked: OptIn"/>
</div>
</div
var ViewModel = function () {
var self = this;
self.OptIn = ko.observable(false);
self.OptIn2 = ko.observable(false);
}
var appVM = new ViewModel();
ko.applyBindings(appVM);
appVM.OptIn(true);
var content2 = document.createElement('div');
content2.id = 'content2';
content2.innerHTML = '<span>Opt In2</span><input data-val-required="field is required." id="cbOptIn2" name="OptIn2" type="checkbox" data-bind="checked: OptIn2"/>';
document.getElementById('container').appendChild(content2);
appVM.OptIn2(true);
我也尝试通过创建两个单独的视图模型来解决这个问题,但后来我得到了
"You cannot apply bindings multiple times to the same element."
1 回答
我'm assuming your stripped down version is not functionally the same as your actual case and you'使用jQuery load()调用将片段带入 . 如果是这种情况,可以使用几个函数来重新应用绑定:
ko.dataFor()
,ko.cleanNode()
和ko.applyBindings()
.如果要将片段加载到元素中:
并且该元素或其他一些父元素已绑定到视图模型,您可以使用如下函数重新应用绑定:
现在,要使用此功能:
这是有效的,因为即使您可能没有将viewmodel显式应用于正在加载的元素,knockout仍然可以从DOM的上游获取viewmodel .
这种方法唯一真正的警告是
cleanNode
函数;它将删除任何事件处理程序,因此需要重新应用它们(除非你're attaching them to a parent element, in which case you'好) .