Skip to content Skip to sidebar Skip to footer

Knockout Custom Binding Handlers: $root Is Undefined

I am using a Knockout Custom Binding handler (borrowed from Creating groups with Knockout.js foreach). Within the nested markup, I'd like to reference an observable that is located

Solution 1:

The problem is that the original bindingContext is lost in the handler. So when ko.applyBindingsToNode() is called, it uses a completely new context (which is empty). The handler predated when being able to specify what the binding context is, it was added in a later version of knockout. You'll need to make adjustments to the handler to be able to preserve that context.

ko.applyBindingsToNode(element, { foreach: groupedItems }, bindingContext);

So the tweaks you need to make in the handler (removed irrelevant bits to be easier to see):

ko.bindingHandlers.foreachGrouped = {
    // need to get the binding context (fifth param)
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //...//use the normal foreach binding with our new computed
        ko.applyBindingsToNode(element, { foreach: groupedItems }, bindingContext); // pass in the binding context//...
    }
};

updated fiddle

Post a Comment for "Knockout Custom Binding Handlers: $root Is Undefined"