Maxim Eliseev
Maxim Eliseev

Reputation: 3504

Knockout - custom binding inside `with` tag - how to pass "$root " to custom binding?

I have a custom binding inside with tag

<div id="mapContainer" data-bind="with: contentTabs">
  ............
            <div id="map" data-bind="createMap: { }"></div>
  ............
</div>

The custom binding is defined as follows

ko.bindingHandlers.createMap = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
       //Some code which accesses the viewModel
       ....
    }
}

"viewModel" parameter of the custom binding refers to "contentTabs" variable (defined in "with" binding above).

I want to access the view model (root) from the custom binding in a clean way.

Is it possible?

The code worked well before I wrapped the custom binding by "with" binding. - how to pass "$root " to custom binding?

Upvotes: 0

Views: 62

Answers (1)

PW Kad
PW Kad

Reputation: 14995

Just pass in that value as an additional binding -

<div id="map" data-bind="createMap: { }, createMapOptions: { parentContext: $root.something }"></div>

And then in your custom binding get the value of the other bindings -

ko.bindingHandlers.createMap = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var options = allBindingsAccessor().createMapOptions;
        var thisContext = options.parentContext;
    }
}

Upvotes: 1

Related Questions