Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which element was added or removed with a Knockoutjs ObservableArray

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);
});
like image 769
AlignedDev Avatar asked Aug 28 '12 20:08

AlignedDev


People also ask

What is Ko ObservableArray?

If you want to detect and respond to changes of a collection of things, use an observableArray . This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.

How do you update items in ObservableArray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

What is Knockout used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


Video Answer


1 Answers

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/

like image 193
Michael Best Avatar answered Sep 28 '22 05:09

Michael Best