I have been experimenting with using Knockout's bindingProvider
API to bind custom elements, as a way to improve the readability of templates.
In general, my processor is working well for most bindings. However, I am facing an issue with the if binding.
The markup looks like this:
<k-o text="Text" click="clickHandler"></k-o>
<k-o if="IsShowing"><!-- Doesn't work -->
<p>
Hello 1!
</p>
</k-o>
<span data-bind="if: IsShowing"><!-- Works -->
<p>
Hello 2!
</p>
</span>
And here is the code snippet:
ko.bindingProvider.instance.preprocessNode = function(node)
{
if (node.nodeName == 'K-O')
{
var el = document.createElement('span');
var att = document.createAttribute('data-bind');
var attvals = [];
for(var i = 0; i < node.attributes.length; i++)
attvals.push(node.attributes[i].name + ': ' + node.attributes[i].value);
att.value = attvals.join(', ');
el.setAttributeNode(att);
node.parentNode.replaceChild(el, node);
return el;
}
}
Check out the demo on Fiddle: https://jsfiddle.net/whelkaholism/wzqL64ga/
Even though the text and click bindings are functioning correctly, the if binding seems to be causing some trouble. Despite inspecting the object and generated nodes, only the hardcoded ones are working.
(I am utilizing this approach for backend database access applications to enhance functional template clarity during development. Any SEO or related concerns regarding custom elements are not applicable)