我在将常量值传递给回调函数时遇到了一些麻烦。我正在使用 执行RESTful请求ajax
,然后通过将数据返回到回调来处理错误和成功事件,该回调将常量作为第一个参数(SUCCESS 或 ERROR)插入,并将其返回给另一个回调侦听器。唯一的问题是这些新添加的第一个参数没有正确添加(甚至根本没有添加)。我在错误所在的代码中添加了注释。这是小提琴。
(function( REST, $, undefined)
{
REST.get = function(_url, _data, _onSuccessCallback, _onErrorCallback)
{
console.log("GET");
$.ajax({
type: 'GET',
url: _url,
data: _data,
dataType: 'json',
headers: {contentType: 'application/json'},
success: _onSuccessCallback,
error: _onErrorCallback
});
};
}
(window.REST = window.REST || {}, jQuery));
(function( DSP, $, undefined)
{
var baseURL = "www.example.com";
/** The request was successful */
DSP.SUCCESS = 0;
/** The request failed */
DSP.ERROR = 1;
DSP.get = function(url, _data, callback)
{
REST.get(url,
_data,
function(data, text)
{
console.log("Success. arg0 = " + DSP.SUCCESS);
callback.call(DSP.SUCCESS, data, text);
},
function(request, status, error)
{
//So far, it's just errors.
console.log("\nError. arg0 = " + DSP.ERROR);//This prints "Error. arg0 = 1"
for (var i = 0; i < arguments.length; i++)
{
console.log(arguments[i]);//prints the request Object and the text "error"
}
callback.call(DSP.ERROR, request, status, error);//doesn't seem to correctly insert the ERROR constant.
}
);
};
DSP.getSomething = function(callback)
{
console.log("Get something");
var url = baseURL + "/Something";
DSP.get(url, null, function(){
console.log("ARGUMENTS LENGTH = " + arguments.length);//prints 3
for (var i = 0; i < arguments.length; i++)
{
console.log(arguments[i].toString());//prints all same Objects as above
}
if (arguments.length < 1) {
console.error("error in request");
callback.call(null);
}
if (arguments[0] == DSP.ERROR)//should get to here. Why doesn't it???
{
var request = arguments[1];
var status = arguments[2];
var error = arguments[3];
console.error("Failed To Get Something (" + request.responseText + ")");
callback.call(null);
}
else if (arguments[0] == DSP.SUCCESS)
{
var data = arguments[1];
var text = arguments[2];
callback.call(data);
}
else
{
//gets to this line and prints "arguments[0] ([object Object]) != SUCCESS(0) !=ERROR(1)."
console.log("arguments[0] (" + arguments[0].toString() + ") != SUCCESS(" + DSP.SUCCESS + ") != ERROR(" + DSP.ERROR + ").");
console.error("internal error");
callback.call(null);
}
});
};
}
(window.DSP = window.DSP || {}, jQuery));
window.DSP.getSomething(function(response){
if (!response)
{
//this is printed.
console.log("error. No user returned.")
}
else
{
console.log("RESPONSE: " + response.toString());
}
});
我究竟做错了什么?中的错误REST
应该导致DSP.get
将DSP.ERROR
参数作为第一个参数,这应该由getSomething
.