title: "RelativeSource" binding for Knockout template bindings (similar to WPF)
body: <p>I am trying to implement something similar to the WPF concept of RelativeSource bindings for templates in Knockout, in particular the RelativeSource with its mode set to <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.templatedparent%28v=vs.110%29.aspx" rel="nofollow">TemplatedParent</a> .</p>
  
  <p>I have implemented this by overriding the default KO template binding to add $templatedParent to the binding context, as per the code snippet below.</p>
  
  <pre><code> var originalInit = ko.bindingHandlers.template.init,
       originalUpdate = ko.bindingHandlers.template.update;
  
   ko.bindingHandlers.template = {
       init: originalInit,
       update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
           bindingContext['$templateElement'] = element;
           originalUpdate(element, valueAccessor, allBindings, viewModel, bindingContext);
       }
   };
  </code></pre>
  
  <p>This allows the child elements created by the template binding can then use in their <code>data-bind</code> attributes, for example  - </p>
  
  <pre><code>data-bind="style: {backgroundColor: $templateElement.fillColor}"
  </code></pre>
  
  <p>This solution presumes that the template parent element implements a property called <code>fillColor</code> that can be data bound (which I can achieve by making it a web component custom element, and exposing the property as a ko observable).</p>
  
  <p>I am wondering </p>
  
  <ol>
  <li>if anyone else has done something similar to this and </li>
  <li>whether from a design perspective this is a bad idea</li>
  </ol>
  
  <p>Thanks,
  Ian</p>