Search code examples
javascriptjquerybackbone.jsunderscore.js

backbone.js - how and when to show a spinner


Is there any sort of hooks in backbone where I can easily say "whenever any of the collections is fetching data, show the spinner, hide it when they're done"?

I have a feeling it will be more complicated than that and require overwriting specific functions. When should I show the spinner? On fetch() or refresh() or something else?


Solution

  • Backbone doesn't trigger any event when Collection::fetch() starts (see source code), so you will have to override the fetch method. Maybe something like this:

    var oldCollectionFetch = Backbone.Collection.prototype.fetch;
    
    Backbone.Collection.prototype.fetch = function(options) {
        this.trigger("fetch:started");
        oldCollectionFetch.call(this, options);
    }
    

    This will override the fetch method to give you an event when the fetch starts. However, this only triggers the event on the specific collection instance so if you have a bunch of different collections you'll have to listen for that event on each collection.