Subscribe to observable array for new or removed entry only

前端 未结 6 1058
被撕碎了的回忆
被撕碎了的回忆 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

    In order to only detect push() and remove() events, and not moving items, I put a wrapper around these observable array functions.

    var trackPush = function(array) {
        var push = array.push;
        return function() {
            console.log(arguments[0]);
            push.apply(this,arguments);
        }
    }
    var list = ko.observableArray();
    list.push = trackPush(list);
    

    The original push function is stored in a closure, then is overlayed with a wrapper that allows me do do anything I want with the pushed item before, or after, it is pushed onto the array.

    Similar pattern for remove().

提交回复
热议问题