Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js v2.3.0 error "You cannot apply bindings multiple times to the same element"

Tags:

knockout.js

I've just upgraded to Knockout.js 2.3.0 and now I'm getting this error:

You cannot apply bindings multiple times to the same element. 

which I wasn't getting in 2.2.1.

I'm getting a partial view from my MVC controller and adding it to the page after clicking on an href. The error happens the second time I click on the link to get the partial view. I'm doing this multiple times.

Is there a way to clear this out and avoid the new error thrown?

Here's my code:

$.get(url + "GetAssignedCompaniesView?layoutId=" + layoutId + "&noCache=" + new Date().getMilliseconds(), function (result) {     $("#editAssignedPartial").html($(result));     showEditAssignedArea(true);     $(window.document).ready(function () {         // error is thrown here         ko.applyBindings(self, window.document.getElementById("editAssigned"));         $("#layoutId").attr("value", layoutId);         updateTypeHiddenElement.attr("value", "companies");     }); }); 

Here's my HTML:

<div id="area1">     <!-- grid here with links --> </div> <div id="editAssignedPartial"></div> 
$(document).ready(function () {     'use strict';     var vm = new Vm();     ko.applyBindings(vm, document.getElementById("area1")); }); 
like image 421
AlignedDev Avatar asked Jul 17 '13 21:07

AlignedDev


2 Answers

You need to remove the bindings before you use applyBindings again:

ko.cleanNode($element[0]); 
like image 149
vprasad Avatar answered Sep 24 '22 20:09

vprasad


Something that can happen as well which throws this exception is the following. Say you have:

ko.applyBindings(myViewModel1, document.getElementById('element1')); ... ko.applyBindings(myViewModel2, document.getElementById('element2')); 

Now, when both #element1 and #element2 don't exist you'll get the error. The reason is that Knockout's applyBindings falls back on document.body as root element when #element1 and #element2 are not found. Now it tries to apply binding twice on the body...

Not a nice fallback of Knockout if you ask me. I'd rather have a clear error message that the element does not exist in the DOM (yet).

like image 38
Almer Avatar answered Sep 26 '22 20:09

Almer