Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 942
Thiago Miranda de Oliveira Avatar asked Nov 30 '22 14:11

Thiago Miranda de Oliveira


2 Answers

Just use the event "request". It fires when a model (or collection) has started a request to the server. It is available since version 0.9.9.

like image 196
Dennis Avatar answered Dec 24 '22 19:12

Dennis


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
});
like image 34
Casey Foster Avatar answered Dec 24 '22 18:12

Casey Foster