Jeremy Smith
Jeremy Smith

Reputation: 15079

Why am I unable to get the current viewModel in this custom binding?

This is the .haml code that contains my bindings. I removed bindings that weren't relevant.

#date-extension
  .filter-extension-container
    .filter-extension-button
      .button-close
    #hand-graph-container{"data-bind" => "with:dateGraph"}
      #x-axis
      #hand-graph{"data-bind" => "foreach: {data:graphData}"}
        %div{"data-bind" => "interactiveBar: $data"}

And I have the beginnings of a custom binding, like so.

ko.bindingHandlers.interactiveBar = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
debugger;
  },
  update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

  }
};

But when I look at viewModel, it is equal to the valueAccessor and is just the data object that I'm passing in. I'd like access to the dateGraph viewModel, and should be able to access it since I have used "with: graphData" according to the documentation.

Upvotes: 0

Views: 1310

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

Inside of a foreach the viewModel property is the data being bound at that scope level.

There are a couple of options (assuming you are using Knockout 2.0):

  • pass $parent instead of $data and access your dateGraph object via valueAccessor()

  • or the 5th argument to a binding handler is actually the binding context. The binding context will have $data, $parent, $parents, and $root properties. You can see a description of the properties here.

Upvotes: 6

Related Questions