Is it possible to discover the value from a checkbox based field that was unchecked?
I need to programatically add and remove valuelist items on an unrelated dataprovider - and need to know which checkbox was checked or unchecked at a given ondatachange point.
I know I can use oldValue and newValue, and compare lengths to see if data was added or removed, and then, compare values to work out what changed.
However I wonder if there might be a simpler (and less expensive) way to just get the value that was added, or the value that was removed, directly from the ondatachange method.
For anyone interested, I worked out how to do this.
To discover which checkbox value was REMOVED:
if (oldValuesArray.length > newValuesArray.length){
//we removed a value
var removedValue = [];
oldValuesArray.forEach(function(key) {
if (-1 === newValuesArray.indexOf(key)) {
removedValue.push(key);
}
});
var vtheremovedvaluestring = removedValue.join('\n')
var oldRemoveTagsArray = [];
oldRemoveTagsArray = foundset.works_to_tags_join.all_tags.split('\n');
var index = oldRemoveTagsArray.indexOf(vtheremovedvaluestring);
if (index > -1) {
oldRemoveTagsArray.splice(index, 1);
}
var myString = oldRemoveTagsArray.join('\n');
foundset.works_to_tags_join.all_tags = myString
}
and to discover which was added:
if (oldValuesArray.length < newValuesArray.length){
//we added a value
var addedValue = [];
newValuesArray.forEach(function(key) {
if (-1 === oldValuesArray.indexOf(key)) {
addedValue.push(key);
}
});
// application.output(addedValue)
var vtheaddedvaluestring = addedValue.join('\n')
var oldAddTagsArray = [];
oldAddTagsArray = foundset.works_to_tags_join.all_tags.split('\n');
var index = oldAddTagsArray.indexOf(vtheaddedvaluestring);
if (index < 0) {
oldAddTagsArray.splice(2, 0, vtheaddedvaluestring);
}
var myString = oldAddTagsArray.join('\n');
foundset.works_to_tags_join.all_tags = myString
//******************************
}
We frequently have similar functionality and generally use this array difference function to get our results
/**
* Returns the elements from the left array that are missing from the right array
* @param {Array<*>} aLeft
* @param {Array<*>} aRight
*
* @return {Array<*>}
*
*/
function difference(aLeft, aRight)
{
if (!aLeft) {
return [];
}
if (!aRight) {
return [].concat(aLeft);
}
var aDiff = aRight.filter(function (oVal) { return aLeft.indexOf(oVal) == -1 } );
return aDiff;
}
So you end up with something like:
function onDataChange(event, newValue, oldValue) {
var aNew = newValue.split('\n');
var aOld = oldValue.split('\n');
var aRemoved = scopes.array.difference(aOld, aNew);
var aAdded = scopes.array.difference(aNew, aOld);
//Do stuff
}