How to obtain parent template binding values in a nested binding?

knockout.js

Solution

The binding context is passed in as the 5th argument to a binding. So, you can augment that the binding context in your custom binding like `context.$itemType = bindingValue.itemType;`. Sample here: http://jsfiddle.net/rniemeyer/yeN8P/

Another option is to ensure that your `itemType` is available in the `$parent` data. You can do this by passing data to your template like:

`template: {name: 'list', data: { items: items, itemType: 'foo' } }`

So, rather than just passing `items`, now we pass `items` and `itemType`, so from one of the children `$parent.itemType` would contain "foo".

Sample here: http://jsfiddle.net/rniemeyer/yeN8P/1/

Problem

I have a knockout template like this: ``` <script type="text/html" id="list"> <ul data-bind="foreach: items"> <li data-bind="{text: name}"></li> </ul> </script> ``` That I use like this: ``` <div data-bind=" template: {name: 'list', data: itemList}, myBinding: {itemType: 'foo'} "></div> ``` I have a `myBinding` custom binding handler: ``` ko.bindingHandlers.myBinding = { init: function(element, valueAccessor) { var bindingValue = valueAccessor(); alert ( bindingValue.itemType ); // alerts "foo" // now set up a jQuery click handler $(element).on("click", "li", listItemClickHandler); } }; ``` And an event handler: ``` function listItemClickHandler() { var bindingContext = ko.contextFor(this); alert( "bindingValue.itemType ???" ); }); ``` Is there a way to get the `itemType` of the parent template, as provided in the custom binding, in the click handler though knockout's `bindingContext`? - Without adding some bogus CSS class like `.type-foo` to the `<ul>` (that's what I do now). - Without storing `"foo"` in the array item during `myBinding.init()`. - Without in-lining the event handler to take advantage of the closure variable (`bindingValue`). - Without using jQuery's `event.data` facility. I could do that, but I'd like to retrieve it from knockout's binding context, unless that's impossible.

Original source