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);
});
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.
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 :).
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With