Subscribe to observable array for new or removed entry only

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

    None that I know of. Wanna know what I do? I use a previous variable to hold the value, something called selectedItem

    vm.selectedItem = ko.observable({});
    function addToArray(item) { vm.selectedItem(item); vm.myArray.push(item); }
    

    So that way, when something happens to my observable array, I know which item was added.

    vm.myArray.subscribe(function(newArray) { var addedItem = vm.selectedItem(item); ... }
    

    This is really verbose, and assuming your array holds many kinds of data, you would need to have some sort of flags that helps you know what to do with your saved variables...

    vm.myArray.subscribe(function(newArray) {
      if ( wasUpdated )
        // do something with selectedItem
      else
        // do whatever you whenever your array is updated
    }
    

    An important thing to notice is that you might know which item was added if you know whether push or unshift was used. Just browse the last item of the array or the first one and voila.

提交回复
热议问题