I have nested custom knockout bindings.
The top level binding extends the binding context and and adds to it.
The child binding needs to be a child binding because it uses the data added to the binding context.
Psuedo-code -
ko.bindingHandlers.map = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
let map = new map({element: element});
let innerBindingContext = bindingContext.extend({"map": map});
ko.applyBindingsToDescendants(innerBindingContext, element);
// tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true };
}
};
ko.bindingHandlers.overlay = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
let map = bindingContext.map;
let overlay = new overlay({element: element});
map.addOverlay(overlay);
// have tried 1. code below,
// 2. createChildContext,
// 3. not returning anything,
// 4. ko.cleanNode(element); prior to binding,
// all with the same error
let innerBindingContext = bindingContext.extend({});
ko.applyBindingsToDescendants(innerBindingContext, element);
return { controlsDescendantBindings: true };
}
};
var vm = {
someVariable: ko.observable("test");
}
ko.applyBindings(vm);
HTML -
<div data-bind="map:{}">
<div data-bind="overlay:{}">
<span data-bind="text:someVariable"></span>
</div>
</div>
No matter what I do, I get the error -
"You cannot apply bindings multiple times to the same element."
The bindings are actually making use of a javascript library. This library moves the childbinding dom element elsewhere in the HTML. And I think this is the problem.
Why am I getting this error due to the dom element being moved, and how do I resolve this?
ko.cleanNode(element);to the very top of your map binding handler instead. That might remove the whole block from the binding hierarchy. - Jason Spake