Knockout.js Custom Tags

by lelandrichardson

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<abc>
    <div data-bind="text: label"></div>
</abc>



<template id="ko-tag-abc">
    Test Content
    <content></content>
    More Content
</template>

JavaScript

ko.tags = {
    "abc": {
        template: '#ko-tag-abc'
    }
};

ko.bindingProvider.instance.preprocessNode = function(node) {
    if (node.nodeType !== 1) {
        return;
    }
    
    var name = node.tagName.toLowerCase(),
        tag;
    
    if (tag = ko.tags[name]) {
        var attributes = node.attributes,
            options = {};
        
        for (var i = 0; i < node.attributes.length; i++) {
            var attrib = node.attributes[i];
            
            if (attrib.specified) {
                options[attrib.name] = attrib.value;
            }
        }
        
        if (tag.init) {
            tag.init(options);    
        }
        
        if (tag.template) {
            var $template = $(tag.template).clone(),
                $node = $(node);
            
            $template
                .find("content")
                .replaceWith($node.html());
            $node.replaceWith($template);
            
        }
    }
};

ko.applyBindings({});