JSFiddle - React, Tailwind, and code Playground

by angstrey

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<ul data-bind="foreach: products">
    <li class="product">
        <strong data-bind="text: name"></strong>
        <like-widget params="value: userRating"></like-widget>
    </li>
</ul>

CSS

body {
    font: 1em/1.4em Arial;
}
ul, li {
    list-style: none;
    margin: 0;
    padding: 0;
}

.product {
    background: #ccc;
    border: solid 1px #999;
    border-radius: 10px;
    margin-bottom: 10px;
    padding: 10px;
}

JavaScript

(function (ko) {
    ko.components.register('like-widget', {
        viewModel: function (params) {
            var self = this;
            
            // Value is either null, "like", or "dislike"
            self.chosenValue = params.value;
            
            self.like = function () {
                self.chosenValue("like");
            };
            
            self.dislike = function () {
                this.chosenValue("dislike");
            };
        },
        template: '\
            <div class="like-or-dislike" data-bind="visible: !chosenValue()">\
                <button data-bind="click: like">Like</button>\
                <button data-bind="click: dislike">Dislike</button>\
            </div>\
            <div class="result" data-bind="visible: chosenValue">\
                You <strong data-bind="text: chosenValue"></strong> it\
            </div>\
            '
    });
    
    function Product(name, rating) {
        this.name = name;
        this.userRating = ko.observable(rating || null);
    }
    
    function AppViewModel() {
        this.products = [
            new Product("Garlic Bread"),
            new Product("Pain au chocolat"),
            new Product("Seagull spaghetti", "like")
        ];
    };
    
    ko.applyBindings(new AppViewModel());
})(window.ko);