GeForce RTX 4090
GeForce RTX 4090

Reputation: 3508

Execute a function whenever a property of an observable changes in Knockout JS

I have a demo application where all the list items are observables. To achieve this I have used the mapping plugin on the array from which the list is created.

this.allItems = ko.mapping.fromJS([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);

My question is - how to properly implement this kind of behavior in Knockout JS: whenever a property of an observable(any item of the list) changes a sort function is executed:

    this.sortList = function() {
    this.allItems(this.allItems().sort(function(a, b) { return a.name() > b.name();}).slice(0, 2));
};

Upvotes: 0

Views: 53

Answers (1)

Alon
Alon

Reputation: 11935

First, you need to declare a view model class. Then, declare allItems as an observable array, but display to the user a different member, called say sortedItems, which should be a computed field. This computed field will use allItems internally, so KO will notice when allItems gets updated and will re-evaluate sortedItems too.

function AppViewModel() {
var self = this;

this.allItems = ko.observableArray([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"}
]);

    this.sortedItems = ko.computed(function() {
        return self.allItems().sort(sortFunction);
    }, this);
}

Upvotes: 1

Related Questions