confirmations hash in AJAX
if you write feature rich applications, you often come to a point where user actions could potentially discard changes or delete things. might be that some element is discarded or all the changes are lost. this is always the point where you have to ask the user, whether this is wanted. usually this leads into some design problem. in every related function you have to check, whether changes have been made and react. the amount of additional code is huge. this is why recently handgestrickt developed a confirmations hash, where we name confirmations and combine them with functions. every function, that potentially can delete data, checks now, whether some entries exist and asks the questions. the best is, it is very simple to implement and small. the function:
var foo = {
confirm_hash = {};
confirm: function(confirmations) {
if(
this.confirm_hash &&
this.is_hash(this.confirm_hash)
) {
if(confirmations && this.is_array(confirmations) && confirmations.length > 0) {
for(var a=0;a<confirmations.length;a++) {
if(this.confirm_hash[confirmations[a]]) {
var func = this.confirm_hash[confirmations[a]];
if(!func()) return false;
this.confirm_hash[confirmations[a]] = null;
}
}
}
else {
for(var key in this.confirm_hash) {
var func = this.confirm_hash[key];
if(!func()) return false;
}
this.confirm_hash = {};
}
}
return true;
},
is_hash: function(value) {
return (value && typeof(value) == 'object' && typeof(value.length) != 'number');
},
is_array: function(value) {
return (value && typeof(value) == 'object' && typeof(value.length) == 'number');
}
}
now let's see how to use it. if you do not give an argument, the whole hash of confirmations will be questioned. if you provide an array of named confirmations, those confirmations will be questioned. here is an example of how to use it:
var foo = {
//...here the confirm stuff...
//some nonsense properties
a: 0,
b: 1,
c: 2,
change_something: function() {
this.a = this.b; //we do nonsense here
if(!this.confirm_hash['discard_changes']) this.confirm_hash['discard_changes'] = this.discard_changes;
},
change_another_thing: function() {
this.b = this.c; //we do nonsense here
if(!this.confirm_hash['discard_element']) this.confirm_hash['discard_element'] = this.discard_element;
},
go_to_some_other place: function() {
if(this.confirm(['discard_changes','discard_element'])) location.replace('http://www.google.com');
},
delete_another_thing: function() {
if(this.confirm(['discard_element'])) this.b = this.a; //we do nonsense here
},
discard_changes: function() {
return window.confirm('do you really want to delete all changes?');
},
discard_element: function() {
if(this.b == this.c) { //do some nonsense test here
return window.confirm('do you really want to delete this element?');
}
else return true;
}
}
in every function of your application you just ask for specific entries in the confirm_hash. that is one line of code per function. tricky, eh?

