I am interested in using named templates with a custom bindingHandler in knockout, but I have encountered an issue where the viewModel passed into the custom binding does not include the context properties of $root, $parent, $component, etc., which are necessary in my scenario.
Whenever I attempt to use ko.renderTemplate on a template that references $parent, I am met with an error message - "ReferenceError: $parent is not defined"
NOTE: The mention of binding to the object "bob" serves to illustrate the need for accessing "bob's" $parent. While I can obtain the context for the parent viewModel by using ko.contextFor(element), I specifically require the context of the "bob" object...
JAVASCRIPT:
ko.bindingHandlers.test = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var templateId = ko.unwrap(valueAccessor());
console.log(templateId);
ko.renderTemplate(templateId, viewModel, {}, element, "replaceChildren");
}
};
var viewModel = function() {
this.bob = {
name: ko.observable("bob")
};
this.numberOfClicks = ko.observable(0);
this.registerClick = function(ctx) {
console.log(ctx);
this.numberOfClicks(this.numberOfClicks() + 1);
};
};
ko.applyBindings(new viewModel());
HTML
<div>You've clicked <span data-bind='text: numberOfClicks'> </span> times</div>
<div data-bind="with:bob">
<span data-bind="test:'testTemplate'"></span>
</div>
<script id="testTemplate" type="text/html">
<span data-bind="text:name" />
<button data-bind="click:$parent.registerClick">CLICK</button>
</script>