JSFiddle - React, Tailwind, and code Playground

by drulia

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<div id="con">
    <h3 data-bind="text: title"></h3>
    <div id="list"></div>
</div>
<button id="btn">Do it again</button>

CSS

.red {
    background: red;
}
.green {
    background: green;
}
.blue {
    background: blue;
}
.yellow {
    background: yellow;
}

JavaScript

var con  = document.getElementById('con'),
    list = document.getElementById('list'),
    btn  = document.getElementById('btn'),
    fruits  = [{
        color: 'red',
        name: 'Apple'
    }, {
        color: 'blue',
        name: 'Orange'
    }, {
        color: 'green',
        name: 'Pear'
    }, {
        color: 'yellow',
        name: 'Lemon'
    }];

var mainVM = function() {
	this.title = ko.observable('Title of some sort');
    this.klass = function(fruit) {
    	return fruit.color;
    }
};
function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

function applyBindings() {
	var frag = document.createDocumentFragment(),
        bindingContext = ko.contextFor(list);

    shuffle(fruits).map(function(fruit) {
      var el = document.createElement('div');
      el.innerText = fruit.name;
      el.setAttribute('data-bind', 'css: $parent.klass($data)');
      var childContext = bindingContext.createChildContext(fruit);
      ko.applyBindings(childContext, el);
      frag.appendChild(el);
    });
    
    while(list.lastChild) {
        ko.cleanNode(list.lastChild);
        list.removeChild(list.lastChild);
    }
    
    list.appendChild(frag);
}

btn.addEventListener('click', applyBindings);

ko.applyBindings(new mainVM, con);