我编写了以下JavaScript类:
var DbObject = Class.extend({
init: function(classname, id){
// do some init stuff
},
send: function(isError){
if(isError){
// do something else
}
else if(!uploading){ // global
var obj =$.parseJSON(JSON.stringify(this));
$.ajax({
type: "POST",
dataType: "json",
url: "ajaxManager.php",
data: {data:obj},
success: function(response) {
response.success=true;
if(response.callback) window[response.callback](response);
console.log(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
else{
console.log('waiting....');
var $this =this;
setTimeout(function(){$this.send(); }, 2000);
}
}
});
现在,我使用这样的类:
var object = new DbObject('PageSettings', rowId);
object.send();
我希望能够像这样使用它:
var object = new DbObject('PageSettings', rowId);
object.send(false, {
success: function (response) {
// some alternate code to run instead of the ajax `success: function`
},
error: function (xhr, status, error) {
// some alternate code to run instead of the ajax `error: function`
}
});
{ success: //...., error: //...}
调用中提供的.send()
应该替换它所进行的ajax调用中的{ success: //...., error: //...}
。
实现这一目标的正确方法是什么?
答案 0 :(得分:2)
像这样更改发送功能:
public class AuthorizedMediaHandler : IHttpHandler, IDependency
{
private readonly IAuthenticationService _authenticationService;
public AuthorizedMediaHandler(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
// Do something using the injected services...
}
}
答案 1 :(得分:1)
这是承诺的完全自然。您所要做的就是从ajax调用中返回promise,然后您的调用者可以直接使用promise而无需知道内部发生的事情:
var DbObject = Class.extend({
init: function (classname, id) {
// do some init stuff
},
send: function (isError) {
if (isError) {
// handle synchronously, but still return a promise so
// the caller gets the same behavior
$(someSelector).show();
return $.Deferred().resolve(false).promise();
} else if (!uploading) { // global
var obj = $.parseJSON(JSON.stringify(this));
return $.ajax({
type: "POST",
dataType: "json",
url: "ajaxManager.php",
data: {
data: obj
}
});
} else {
console.log('waiting....');
var self = this;
return $.Deferred(function(def) {
// now set up delayed execution
setTimeout(function () {
def.resolve();
}, 2000);
}).then(function() {
// link this into the existing promise chain
return self.send();
});
}
}
});
并且,样本用法:
var db = new DbObject('PageSettings', rowId);
db.send().then(function (result) {
// success here
}, function (err) {
// error here
});