JSFiddle - React, Tailwind, and code Playground

by psteele

HTML

<!-- works once, but doesn't see updates to the array. note no parenthesis -->
<ul data-bind="foreach: people.sort(sortByAge)">
    <li data-bind="text: name"></li>
</ul>

<hr/>

<!-- works all the time (sees updates to the array). note use of parenthesis -->
<ul data-bind="foreach: people().sort(sortByAge)">
    <li data-bind="text: name"></li>
</ul>

JavaScript

function ViewModel() {
    var self = this;
    
    self.people = ko.observableArray([
        { name: 'Bob', age: 22 },
        { name: 'Sue', age: 12 },
        { name: 'Jill', age: 20 }
    ]);
    self.sortByAge = function(l,r) {
        if( l.age === r.age )
            return 0;
        return (l.age > r.age) ? 1 : -1;
    };
    self.addMike = function() {
        self.people.push({name: 'Mike', age: 16 });
    };
    self.sortedPeople = ko.computed(function() {
        return self.people().sort(this.sortByAge);
    })
}

var vm = new ViewModel();
ko.applyBindings(vm);
// add a new person after 2 seconds
setTimeout(vm.addMike, 2000);