Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Backbone uses jQuery (see the note for a solution that may work with Zepto) for ajax requests, so you can use (as suggested by Edward) <a href="http://api.jquery.com/jQuery.ajaxPrefilter/" rel="nofollow">jQuery.ajaxPrefilter</a>.</p> <p>I did a little test for this task, let me know if there's any problem:</p> <pre><code>function tokenIsExpired() { return true; } function createPromiseFunction(method, jqXHRsource, jqXHR) { return function() { jqXHRsource[method] = function(f) { if (f) { jqXHR[method] = function() { f.apply(this, arguments); }; } return this; }; } } function updateToken() { return $.ajax({ url: '', method: 'GET', data: {some:'data', here:'yes'}, success: function() { // update the token sir console.log('token call done') }, skipTokenCheck: true // required }); } $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { /* * check if token is expired every time a new ajax request is made * if it is expired, aborts the current requests, updated the token * and eventually does the original request again. */ if (!options.skipTokenCheck &amp;&amp; tokenIsExpired()) { // at this point no callback should have be added to the promise object var methodsNames = [ 'done', 'always', 'fail', 'progress', 'then' ]; var methods = {}; // copy the callbacks when they're added to the old request for (var i = 0; i &lt; methodsNames.length; i++) { var name = methodsNames[i]; createPromiseFunction(name, jqXHR, methods)(); }; jqXHR.abort(); // TODO: error checks updateToken().done(function() { console.log('done'); var newReq = $.ajax($.extend(originalOptions, {skipTokenCheck: true})); for (var i = 0; i &lt; methodsNames.length; i++) { var name = methodsNames[i]; var f = methods[name]; if (f) { newReq[name](f); } }; }); } }); var p = $.get('.'); p.done(function() { console.log(arguments); }).fail(function() { console.log('fail'); }); </code></pre> <p>Looks like that ajaxPrefilter doesn't work with Zepto. Alternatively you can use the <a href="http://api.jquery.com/Ajax_Events/" rel="nofollow">ajaxBeforeSend</a> event.</p> <blockquote> <p>Returning false in the beforeSend function will cancel the request.</p> </blockquote> <p>Should be easy to adapt the code I posted above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload