I have view model that I created in an ajax application. The ko.applyBindings() gets called when I render my first piece of html. Later I make a second ajax call to render another section of html and bind to the same view model. However, because the html elements from the 2nd ajax were not present when I first called ko.applyBindings() then when my second section of html is retrieved, data-bind does not work.
Here's a very simple example where the first check box binds correctly. Then content2 would be loaded via a subsequent ajax call and the checkbox fails to bind
<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);
I have also tried to solve this by creating two separate view models but then I get
"You cannot apply bindings multiple times to the same element."
applybindingsmultiple times that how ko works .but you can try usingcleanNodeand re-applying bindings on the main div should work fine . cheers - super coolhide itand inside ajax successshowit . cheers - super coolself.optInList = ko.observableArray([OptIn, OptIn2])and then the DOM will be updated via a<div id="content1" data-bind="foreach: optInList">. Then when your Ajax call fetches new optIn items, you push them into the list and the DOM updates, bindings and all. - sifriday