Search code examples
backbone.jsbackbone-events

BackboneJS before fetch event


I have a collection ( using the Backbone.paginator ) that fetchs a array of models from the server and return to me. This collection is used on my "main view" and on "subviews". In each of these views I have a on("change") event that, in each view, does a particulary thing. I was thinking if I can listen to some "start fetch" event ( similar to the beforeLoad on the jquery) to add a loader gif. Does Backbone provide one of this?

If not.. How can I extend it?

Thanks!


Solution

  • You can extend the Backbone Collection prototype like this:

    (function() {
      var fetch = Backbone.Collection.prototype.fetch;
      Backbone.Collection.prototype.fetch = function() {
        this.trigger('beforeFetch');
        return fetch.apply(this, arguments);
      };
    })();
    

    Now you can do something like:

    myCollection.on('beforeFetch', function() {
      // take care of before fetch business
    });