Knockout - determine what was removed
For SO question. http://stackoverflow.com/questions/12166982/determine-which-element-was-added-or-removed-with-a-knockoutjs-observablearray
by logankd
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<table>
<tbody data-bind="foreach: dataPointOptions">
<tr>
<td>
<input type="checkbox" data-bind="value: $data, checked:selectedDataPointOptions" /></td>
<td><span data-bind="text: $data"></span></td>
</tr>
</tbody>
</table>
JavaScript
// updated with answer from SO
// function from http://jsfiddle.net/mbest/Jq3ru
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;
});
};
ViewModel = function() {
// data point options, the user can select and show in the line chart
self.dataPointOptions = ko.observableArray([]);
self.selectedDataPointOptions = ko.observableArray([]);
// old way for the question self.selectedDataPointOptions.subscribe(function(value) {
// how can I see which one was added or removed?
// alert(value);
// });
// new way from the answer
self.selectedDataPointOptions.subscribeArrayChanged(function(value) {
// add to the series
// what's different from the old one?
alert('added ' + value);
}, function(value) {
// removed
alert('removed ' + value);
});
self.getDataPointOptions = function() {
self.dataPointOptions.push("Test");
self.dataPointOptions.push("Test1");
};
self.getDataPointOptions();
};
$(document).ready(function() {
var vm = new ViewModel();
ko.applyBindings(vm);
});