if binding re-evaluated on changes

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<!-- ko if: items.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

ko.observableArray.fn.trackHasItems = function() {
    //create a sub-observable
    this.hasItems = ko.observable();

    //update it when the observableArray is updated
    this.subscribe(function(newValue) {
        this.hasItems(newValue && newValue.length ? true : false);
    }, this);     
    
    //trigger change to initialize the value
    this.valueHasMutated();
    
    //support chaining by returning the array
    return this;    
};

var ViewModel = function() {
    this.items = ko.observableArray().trackHasItems();
    
    this.addItem = function() {
        this.items.push({ name: "item" + this.items().length });
    };
};

ko.applyBindings(new ViewModel());