L.Vardan L.Vardan - 1 month ago 6
Javascript Question

How to stop a collection fetch

I am making a web application with Backbone.js. I have a collection and I need to stop

collection.fetch()
before its end.

Collection

define(['backbone', 'root/config'], function(Backbone, MainConfig){
var supplyChainCollection = Backbone.Collection.extend({
/**Doing a lot of stuff here can`t show**/
});
return supplyChainCollection;
});


Fragment of View

initialize: function(){
this.collection = new SupplyChainCollection();
this.collection.fetch();
},
events :{
'click .close': 'stopFetching'
},
stopFetching: function(ev){
/*need stop fetch here*/
},

Answer

You need to use .abort() method to stop your request. You can do it in this way. I will not write full code only part that you need to change.

In View

initialize: function(){
    this.collection = new SupplyChainCollection();
    this.fetchXhr = this.collection.fetch();
},

stopFetching: function(event){
    event.preventDefault();
    /** If you need to check readystate**/
    if(this.fetchXhr.readyState > 0 && this.fetchXhr.readyState < 4){
        fetchXhr.abort();
    },
    /**else just use **/
       //this.fetchXhr.abort();  
},
Comments