Last active
December 25, 2015 14:59
-
-
Save eduardo-matos/6995006 to your computer and use it in GitHub Desktop.
Delayed AJAX requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define('delayable-xhr', [ | |
'dojo/request/xhr', | |
'dojo/request/util', | |
'dojo/Deferred' | |
], function ( | |
xhr, | |
util, | |
Deferred | |
) { | |
'use strict'; | |
var delayableXhr = function(url, options) { | |
var canceler = function () { | |
window.clearTimeout(timeout); | |
xhrPromise && xhrPromise.cancel(); | |
}; | |
var def = new Deferred(canceler); | |
var xhrPromise; | |
var timeout; | |
if(!options || !options.delay) { | |
return xhr(url, options); | |
} | |
timeout = window.setTimeout(function () { | |
xhrPromise = xhr(url, options).then(function () { | |
def.resolve.apply(this, arguments); | |
}, function () { | |
def.reject.apply(this, arguments); | |
}); | |
}, options.delay); | |
return def.promise; | |
} | |
// ".get", ".post", ".put" and ".del", just like regular xhr | |
util.addCommonMethods(delayableXhr); | |
return delayableXhr; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
'use strict'; | |
$.delayableAjax = function (options) { | |
var args = arguments; | |
var def = $.Deferred(); | |
var promise = def.promise(); | |
var timeout; | |
var xhrPromise; | |
def.abort = promise.abort = function () { | |
window.clearTimeout(timeout); | |
xhrPromise && xhrPromise.abort(); | |
}; | |
if(args.length !== 1) { | |
return $.ajax.apply(this, args); | |
} | |
if(!options || !options.delay) { | |
return $.ajax(options); | |
} | |
timeout = window.setTimeout(function () { | |
xhrPromise = $.ajax(options).done(function () { | |
def.resolveWith(this, arguments); | |
}).fail(function () { | |
def.rejectWith(this, arguments); | |
}); | |
}, options.delay); | |
return promise; | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment