knockout list & buttons

by andyjmeyers

HTML

<script type='text/html' id='nodeTemplate'>
    <li><div class='nodeContainer'>
        <input type='text' data-bind="value: name" />
        <button class='delete' data-bind='visible: $root != $data, click:function(){  $parent.children.remove($rawData);}'>&nbsp;</button>
    </div>
    <div>
        <h5 data-bind="visible: children().length > 0">Children</h5>
        <ul data-bind="template: {name: 'nodeTemplate', foreach:children}">
        </ul>
        <button class='add' data-bind='click: function(){ $data.addChild();}'>Add child</button>
    </div>
    </li>
</script>

<ul  data-bind='template: {name: "nodeTemplate",data: $root}'>
</ul>

CSS

ul{
    list-style-type: none;
}

button.delete{
    background: url('https://googledrive.com/host/0B4QQSpfhQZN5RUJPLVg3TU9iNzg/remove.ico');
    background-size:   cover;                      
    background-repeat: no-repeat;
    border:0;
    background-color:transparent;
    cursor:pointer;
}
button.delete:active{
    outline:none;
}

button.add{
    border:0;
    background-color:transparent;
    text-decoration:underline;
    color:blue;
    cursor:pointer;
}
button.add::before{
    content:url("https://googledrive.com/host/0B4QQSpfhQZN5RUJPLVg3TU9iNzg/arrows_4_way.png");
}

button.add:active{
    outline:none;
}

JavaScript

(function(ko){
    function Node(name){
        this.name = ko.observable(name);
        this.children = ko.observableArray();
    }
    
    Node.prototype = {
        addChild: function(){
            this.children.push(ko.observable(new Node()));
        }
    };
    window.VM = new Node("Root");
    ko.applyBindings(window.VM);
    
})(ko);