How do I subclass the jQuery ajax object or reuse a common callback?
I'm sorry for ambiguous title, but this question is hard for me to put into words, I can only seem to describe it with code.
I have the following function
function initRPC(procedureName, parameters)
{
var parcel = //some code that parcels up the procedure name and params
$.get(
'url' : 'rpcserver.php',
'data' : parcel,
'success' : function(returnXML) {
unparcel = //some code to unwrap the returned data
/**
* now instance specific code
*/
}
);
}
Where it says now instance specific code
is where I want to specific code, and to reuse the rest as initRPC will be called frequently.
For example I'd like to initiate the initRPC like this:
function getUsername()
{
alert('Your name is: ' + initRPC('getUsername', { id: someVar }));
}
or like this (in this example the signature of the initRPC command would extend 开发者_JAVA技巧to include the passed function reference, but I don't know how to pass that reference to the $.post callback:
function getUsername()
{
initRPC('getUsername', {id: someVar}, function todoAfterUnWrap(data) {
alert('Your name is: ' + data);
});
}
I can't see a way of doing what I hoped, it feels like I will always have to repeat the $.ajax() call with unwrapping and wrapping in each function (like getUsername()).
Rephrased: How do I encapsulate data preparation code, the AJAX request, and unwrapping code together and then allow for instance specific code to run after those. Asynchronously.
[edit]The idea coming to me now is the typical way of reusing code in this situation is as follows:
function getUsername()
{
var request = prepareRequest('getUsername', { id: someVar });
$.get(
'url' : 'rpcserver.php',
'data' : request
'success' : function(response) {
response = decodeResponse(response);
/* instance specific code */
}
);
}
Perhaps this is the only way, it just seems to me to require repeating much of the same code in each function like getUsername()
If the idea is to post a callback function, that's fairly easy. You could keep your code as provided in this example:
function getUsername()
{
initRPC('getUsername', {id: someVar}, function todoAfterUnWrap(data) {
alert('Your name is: ' + data);
});
}
And write initRPC like this:
function initRPC(procedureName, parameters, callbackFn)
{
var parcel = //some code that parcels up the procedure name and params
$.get(
'url' : 'rpcserver.php',
'data' : parcel,
'success' : function(returnXML) {
unparcel = //some code to unwrap the returned data
callbackFn(unparcel);
});
}
精彩评论