Knockout - pluralize values

by forivall

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-debug.js"></script>
<div>
    <p>using computed</p>
    <ul data-bind="foreach: products">
        <li><span data-bind="text:qty"></span>&nbsp;<span data-bind="text:formattedName"></span></li>
    </ul>
    <br/>
    <p>using conditionals</p>
    <ul data-bind="foreach: products">
        <li><span data-bind="text:qty"></span>&nbsp;<span data-bind="text:name"></span><span data-bind="if:qty()>1">s</span></li>
    </ul>
</div>

JavaScript

var Product = function() {
    this.name = ko.observable();
    this.qty = ko.observable();
    this.formattedName = ko.computed(function() {
        return this.qty() > 1 ? this.name() + "s" : this.name();
    }, this);
};

var vm = function ViewModel() {
    this.products = ko.observableArray([
        new Product().name("strap").qty(7),
        new Product().name("pick").qty(1),
        new Product().name("capo").qty(2)]);
};

ko.applyBindings(new vm());