Determine which element was added or removed with a Knockoutjs ObservableArray

datatables, knockout.js

Solution

Knockout includes `ko.utils.compareArrays` which you can use to compare one array to another. Here's a helper function that notifies for each added or removed item in the array:

ko.observableArray.fn.subscribeArrayChanged = function(addCallback, deleteCallback) {
    var previousValue = undefined;
    this.subscribe(function(_previousValue) {
        previousValue = _previousValue.slice(0);
    }, undefined, 'beforeChange');
    this.subscribe(function(latestValue) {
        var editScript = ko.utils.compareArrays(previousValue, latestValue);
        for (var i = 0, j = editScript.length; i < j; i++) {
            switch (editScript[i].status) {
                case "retained":
                    break;
                case "deleted":
                    if (deleteCallback)
                        deleteCallback(editScript[i].value);
                    break;
                case "added":
                    if (addCallback)
                        addCallback(editScript[i].value);
                    break;
            }
        }
        previousValue = undefined;
    });
};

Here it is in action: http://jsfiddle.net/mbest/Jq3ru/

Beginning with Knockout 3.0, you can use the `arrayChange` event to do this more easily. More info is here: http://blog.stevensanderson.com/2013/10/08/knockout-3-0-release-candidate-available/

Problem

I need to figure out which element was removed from my Knockout observableArray. Please see my jsFiddle. I can subscribe to the change, but it only returns value, which is the current array after the add or remove. ``` self.selectedDataPointOptions.subscribe(function(value) { // how can I see which one was added or removed? alert(value); }); ```

Original source