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-footo the<ul>(that’s what I do now). - Without storing
"foo"in the array item duringmyBinding.init(). - Without in-lining the event handler to take advantage of the closure variable (
bindingValue). - Without using jQuery’s
event.datafacility. I could do that, but I’d like to retrieve it from knockout’s binding context, unless that’s impossible.
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
itemTypeis available in the$parentdata. 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 passitemsanditemType, so from one of the children$parent.itemTypewould contain “foo”.Sample here: http://jsfiddle.net/rniemeyer/yeN8P/1/