Skip to content

Instantly share code, notes, and snippets.

@vicentereig
Created November 26, 2014 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vicentereig/c4a0cb65751ec23d188c to your computer and use it in GitHub Desktop.
Save vicentereig/c4a0cb65751ec23d188c to your computer and use it in GitHub Desktop.
ember-cli-ember-data-cancelable

Cancel XHR Requests in Ember Data

This feature is useful in search-as-you-type components to rely on the backend to perform the search. For example, http://hola-apps.herokuapp.com/apps/search?term=farts

Following this great comment in Stackoverflow. This ember addon will extend DS.RESTAdapter initially to be able to cancel an on going HTTP request by invoking store.cancelQuery('resourceType')

import DS from "ember-data";
import Ember from "ember";

export default DS.RESTAdapter.extend({
    jqXHRs: [],
    ajaxOptions: function(url, type, hash) {
        // Get default AjaxOptions
        var ajaxOptions = this._super(url, type, hash);

        // If the function was defined in the DS.RESTAdapter object,
        // we must call it in out new beforeSend hook.
        var defaultBeforeSend = function(){};
        if(typeof ajaxOptions.beforeSend === 'function'){
            defaultBeforeSend = ajaxOptions.beforeSend;
        }
        ajaxOptions.beforeSend = function(jqXHR, settings){
            defaultBeforeSend(jqXHR, settings);
            this.jqXHRs.push(jqXHR); // Keep the jqXHR somewhere.
            var lastInsertIndex = this.jqXHRs.length - 1;
            jqXHR.always(function(){
                // Destroy the jqXHRs because the call is finished and
                // we don't need it anymore.
                this.jqXHRs.splice(lastInsertIndex,1);
            });
        };

        return ajaxOptions;
    },

    cancelQuery: function(){
        this.jqXHRs.forEach(function(req){
            req.abort();
        });
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment