knockout example

by Richard Hunter

HTML

<div id="container">
    <nav> 
        <ul id="links"> 
            <li><a href="foo" data-bind="click: handleLink">foo</a></li>
            <li><a href="bar" data-bind="click: handleLink">bar</a></li> 
        </ul>
    </nav> 
    <article class="article">
        <div data-bind="template: { name : template, data : data }"></div>    
    </article>
</div>

<script type="text/html" id="foo-template">
    <h1 data-bind="text: title">Foo foo</h1>
    <div data-bind="text: body">
        It's the end foo foo balh dkjfdkj kjd jk 
    </div>    
</script>
<script type="text/html" id="bar-template">
    <h1 data-bind="text: title">Bar</h1>
    <div data-bind="text: body">
        It's the end bar bar balh dkjfdkj kjd jk 
    </div> 
    <div data-bind="click: apple">apple</div>
</script>

SCSS

.article {
    
    width : 400px;
    margin : 100px auto;
    display : block;
    
}

JavaScript

function getData(href) {

    if ( href==="foo" ) {   
        return {
            title : ko.observable("this is a foo"),
            body : "it's the end of the world as we know it and I feel fine"
        };
    } else {
        return {
            title : ko.observable("this is a bar"),
            body : "ilala love you don't mean maybe",
            apple : function() {
                alert("this is an apple");
            }
        };    
    }
}

var self = {
    
    template: ko.observable("foo-template"),
               
    handleLink : function (model, event) {
        
        event.preventDefault();           
        var href = event.target.getAttribute('href');  
        model.data = getData(href)
        model.template(href + "-template");
        
    },
    
    data : {
        title : "this is foo",
        body : "this is a body"
    
    }
    
}

ko.applyBindings(self, document.querySelector('#container'));