In a jQuery ajax request, I have error handling that happens with callback:
success: function(a) {
if (a.error) switch (a.error) {
case "formError":
case "clientError":
case "limitError":
doErrorCorrection();
alert("Client-sided error: " + a.errorMessage);
break;
case "serverError":
case "500Error":
doRollback();
doTransactions();
break;
case "generalError":
alert("One plus one is: " + (1+1));
} else doActionsWith(a)
}
I would like to move this into an object of it's own such as:
var errors = {
...
formError: function() {...},
generalError: function() {...},
...
};
With that, I could say:
success: function(a) {
if (a.error) return errors[a.error](a.errorMessage);
doActionsWith(a)
}
The issue is that I have tons of reflow from switch, and if I were to translate this to an object, that would mean repetition of the same functions over and over.
var errors = {
formError: function() { methodA() },
clientError: function() { methodA() },
limitError: function() { methodA() },
...
//more if I had more reflows
};
So I thought of having an array/list as the index. I messed around setting an index like:
var arr = {
test: 'hello world'
};
var index = ['a', 'b', 'c'];
arr[index] = 'array as index';
It worked, but only partially. When I ran the keys through, they returned as a string:
for (var key in arr) console.log(key)
//test
//a,b,c
Running the same test with an object, index = {'a' = true} only set the string index object Object to array as index.
Okay, so an array/object as an index won't work, how should I restructure my switch into an object?
{ formError: function() { methodA() } }is the same as{ formError: methodA }for..inloop worked for you with object keys but not with an object? btw. your second objectindex = { 'a' = true }is incorrect, should beindex = { 'a': true }