4

Consider the following example:

ko.applyBindings(viewModel, document.getElementById('id'));

Is there some way via using knockout to get a list of "applied bindings?" I ask because I have a situation where I am getting the dreaded:

Uncaught Error: You cannot apply bindings multiple times to the same element.

Now its pretty obvious what the error means. How ever with how we do things, we load a view to the page via ajax and use the $(id).html(data) to populate the page with the said view and then after use require js to load the view and then apply the bindings.

Now this works, until we navigate to another widget which, according to how we do things, should replace the current view and view model (binding) on the page. This is where I get the error.

So is there any way to see a current list of "applied bindings" in Knockout at the time it is trying to bind an view model to an element?

TheWebs
  • 12,470
  • 30
  • 107
  • 211

1 Answers1

1

There's a method for an individual element: ko.contextFor. It could be used like this:

console.log(ko.contextFor(document.getElementById("a")));
console.log(ko.contextFor(document.getElementById("b")));
ko.applyBindings({}, document.getElementById("a"));
console.log(ko.contextFor(document.getElementById("a"))); // Only this shows data
console.log(ko.contextFor(document.getElementById("b")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>

<div id="a"></div>
<div id="b"></div>

To get it for all DOM nodes you'd have to iterate/traverse the nodes yourself I think, but that shouldn't be to hard.

Also: don't forget that Knockout is open source, and has an unminified version available. You can catch the error as it's thrown, and check in that context what's going on:

debug session demo

Jeroen
  • 60,696
  • 40
  • 206
  • 339