Declare Ajax-webservicecall OnSuccess method anonymous.
- by user333113
I write a lot of ajax javascript code and have a little design problem which I'm not totally satisfied with.
A lot of times I end up with writing something like this:
var typeOfPopup;
function RetrievePopupContent(_typeOfPopup) {
switch (_typeOfPopup) {
case Popup1: WebService.RetrievePopup1Content(param1, param2, DisplayPopup, OnError);
break;
case Popup2: WebService.RetrievePopup2Content(param1, param2, DisplayPopup, OnError);
break;
}
typeOfPopup = _typeOfPopup;
}
function DisplayPopup(result) {
switch (typeOfPopup) {
case Popup1: $get('Popup1').innerHTML = result;
break;
case Popup2: $get('Popup2').innerHTML = result;
break;
}
Allright. This is a simplified example of what I mean. Often I end up with a lot worse code I believe.
What I don't like is the global state variabel outside the functions.
One solution I wasn't thinking about when writing this code is to send a context object.
I believe you could write something like this:
function RetrievePopupContent(typeOfPopup) {
switch (typeOfPopup) {
case Popup1: WebService.RetrievePopup1Content(param1, param2, DisplayPopup, OnError, typeOfPopup);
break;
case Popup2: WebService.RetrievePopup2Content(param1, param2, DisplayPopup, OnError, typeOfPopup);
break;
}
}
function DisplayPopup(result, typeOfPopup) {
switch (typeOfPopup) {
case Popup1: $get('Popup1').innerHTML = result;
break;
case Popup2: $get('Popup2').innerHTML = result;
break;
}
Is this the recommended way?
What I also want to do is to be able to write something like this:
function RetrievePopupContent(typeOfPopup) {
switch (typeOfPopup) {
case Popup1: WebService.RetrievePopup1Content(param1, param2,
new function(result) {
$get('Popup1').innerHTML = result;
}, OnError);
break;
case Popup2: WebService.RetrievePopup2Content(param1, param2,
new function(result) {
$get('Popup2').innerHTML = result;
}, OnError);
break;
}
}
Is this possible at all? To declare the callback function anonymous? I am grateful for all opinions on the two options I mentioned myself and also new alternatives to get rid of my global variables I have used this way.