refactor request handling

This commit is contained in:
rolux 2013-07-28 01:07:42 +02:00
parent e7415059f0
commit f8da7fa1fb

View file

@ -129,22 +129,21 @@ Ox.Request = (function() {
options.age == -1 options.age == -1
|| options.age > +new Date() - cache[req].time || options.age > +new Date() - cache[req].time
)) { )) {
var data = cache[req].data;
setTimeout(function() { setTimeout(function() {
callback && callback(data); callback(cache[req].data, true);
}, 0); }, 0);
} else { } else {
pending[options.id] = true; pending[options.id] = true;
$.ajax({ $.ajax({
beforeSend: function (request) { beforeSend: function(request) {
var csrftoken = Ox.Cookies('csrftoken'); var csrftoken = Ox.Cookies('csrftoken');
if (csrftoken) { if (csrftoken) {
request.setRequestHeader("X-CSRFToken", csrftoken); request.setRequestHeader('X-CSRFToken', csrftoken);
} }
}, },
complete: complete, complete: complete,
data: options.data, data: options.data,
//dataType: 'json', // dataType: 'json',
timeout: options.timeout, timeout: options.timeout,
type: options.type, type: options.type,
url: options.url url: options.url
@ -155,14 +154,18 @@ Ox.Request = (function() {
}); });
} }
function callback(data) { function callback(data, success) {
if (requests[options.id]) { if (requests[options.id]) {
delete requests[options.id]; delete requests[options.id];
options.callback && options.callback(data);
$element && $element.triggerEvent('request', { $element && $element.triggerEvent('request', {
requests: Ox.len(requests) requests: Ox.len(requests)
}); });
} }
if (success) {
options.callback && options.callback(data);
} else {
$element && $element.triggerEvent('error', data);
}
} }
function complete(request) { function complete(request) {
@ -193,9 +196,9 @@ Ox.Request = (function() {
data: data, data: data,
time: Ox.getTime() time: Ox.getTime()
}; };
callback(data); callback(data, true);
} else { } else {
$element && $element.triggerEvent('error', data); callback(data, false);
} }
pending[options.id] = false; pending[options.id] = false;
} }