if binding re-evaluated on changes

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<!-- ko if: hasItems -->
    <h2>Items</h2>
    <ul data-bind="foreach: items">
        <li data-bind="text: name + ' ' + Date()"></li>
    </ul>
<!-- /ko -->
<button data-bind="click: addItem">Add Item</button>

JavaScript

var ViewModel = function() {
    this.items = ko.observableArray();
    
    this.hasItems = ko.observable(false);
    
    this.items.subscribe(function(newValue) {
        this.hasItems(newValue && newValue.length ? true : false);
    }, this);
    
    this.addItem = function() {
        this.items.push({ name: "item" + this.items().length });
    };
};

ko.applyBindings(new ViewModel());