i have a viewmodel associated with an index page with something like this
// html
<div class="collapse navbar-collapse js-navbar-collapse" id="menuholder">
<ul foreachbinding>
<li binding>
</ul>
</div>
<div id="maincontent">
</div>
// javascript
var VM = function () {
var self = this;
self.menuitems = ko.observableArray([]);
self.loadmenu = function () {
jQuery.ajax({
url: "/Home/GetMainMenu",
success: function (html) {
self.menuitems = html.menus
},
async: false
});
}
self.loadmenu();
};
ko.applyBindings(VM, document.getElementById("menuholder"));
as you can see i am appliying the binding only to the menuholder element .
now i load the content of the maincontent element dynamically with this :
$("#maincontent").load("pages/home.html");
the home.html page has it's own view model like this
//html
<body id="homepage">
</body>
//javascript
var homeVM = function () {
var self = this;
self.topventes = ko.observableArray([]);
self.promos = ko.observableArray([]);
self.arrivage = ko.observableArray([]);
self.nouveaute = ko.observableArray([]);
self.loadcontent = function () {
jQuery.ajax({
url: "/Home/GetHomePageContent",
success: function (html) {
self.topventes = html.topventes;
self.arrivage = html.arrivage;
self.nouveaute = html.nouveaute;
self.promos = html.promo;
},
async: false
});
}
self.loadcontent();
};
ko.applyBindings(homeVM, document.getElementById("homepage"));
but at runtime i get the "cannot apply bindings multiple times to the same element" error .
any idea on what's going on please ?
The root cause is your
home.htmlhas the body tag. It will cause KO to misunderstand the whole structure of the document. Anyway, you cannot putbodytag in that view anyway.Just change
bodytag todivtag, it should be fixed.