Subscribe to observable array for new or removed entry only

前端 未结 6 1050
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 12:39

So yes I can subscribe to an observable array:

vm.myArray = ko.observableArray();
vm.myArray.subscribe(function(newVal){...});

The problem

6条回答
  •  攒了一身酷
    2020-12-08 13:28

    Since I couldn't find any info on this elsewhere, I'll add a reply for how to use this with TypeScript.

    The key here was to use the KnockoutArrayChange interface as TEvent for subscribe. If you don't do that, it'll try to use the other (non-generic) subscribe and will complain about status, index, and value not existing.

    class ZoneDefinition {
        Name: KnockoutObservable;
    }
    
    class DefinitionContainer
    {
        ZoneDefinitions: KnockoutObservableArray;
        constructor(zoneDefinitions?: ZoneDefinition[]){
            this.ZoneDefinitions = ko.observableArray(zoneDefinitions);
            // you'll get an error if you don't use the generic version of subscribe
            // and you need to use the KnockoutArrayChange interface as T
            this.ZoneDefinitions.subscribe[]>(function (changes) {
                changes.forEach(function (change) {
                    if (change.status === 'added') {
                        // do something with the added value
                        // can use change.value to get the added item
                        // or change.index to get the index of where it was added
                    } else if (change.status === 'deleted') {
                        // do something with the deleted value
                        // can use change.value to get the deleted item
                        // or change.index to get the index of where it was before deletion
                    }
                });
            }, null, "arrayChange");
    }
    

提交回复
热议问题