How can I create jQuery as events?
I would like to build a function that calls some event handlers based on the result, like jQuery does $.ajax()
. For example, you can define this ajax code:
$.ajax(
{
url: "http://domainname.tld",
type: 'GET'
}).done(function(e)
{
//succed
}).fail(function(e)
{
//error
});
I would like to receive these
.done(function(e)
{
//succed
}
is blocking my function. At the moment I am doing something like this:
function SendRequest(arg1, arg2, onSuccess, onError)
{
if(true)
{
onSuccess(true);
}
else
{
onError(false);
}
}
and should call it like this
SendRequest("someArg1", "someArg2", function(returnValue) { alert(returnValue); }, function(returnValue) { alert(returnValue); });
and would like to call it like this:
SendRequest("someArg1", "someArg2")
.onSuccess(
function(returnValue)
{
alert(returnValue);
})
.onError(function(returnValue)
{
alert(returnValue);
});
Thanks for pointing me in the right direction!
+3
source to share
1 answer
Thanks to @ arun-p-johny and @hindmost for giving me the correct search keywords and finally solving my problem!
After reading this great article, I came up with the following solution:
function AsyncMethod(arg1, arg2)
{
var deferred = $.Deferred();
//Do your work
if(arg1 == arg2)
{
// true represents the result, optional
deferred.resolve(true);
}else{
// Something went wrong, reject. (false is still the result, therefor it also optional)
deferred.reject(false);
}
return deferred.promise();
}
and calling it like this:
$.when(
AsyncMethod(true, false)
.done(function (returnValue)
{
alert(arg1 + " == " + arg2);
})
.fail(function (returnValue)
{
alert(arg1 + " != " + arg2);
});
);
0
source to share