Skip to content

Instantly share code, notes, and snippets.

@sivagao
Created February 22, 2013 12:51
Show Gist options
  • Select an option

  • Save sivagao/5013195 to your computer and use it in GitHub Desktop.

Select an option

Save sivagao/5013195 to your computer and use it in GitHub Desktop.
Backbone: to indicate Backbone fetch progress , to override a method @ Collection, Model . //patching the fetch method on Collection.prototype to emit a fetch event.
Repos.Views.List = Backbone.View.extend({
initialize: function() {
// Display a loading indication whenever the Collection is fetching.
this.collection.on("fetch", function() {
this.html("<img src='/assets/img/spinner.gif'>");
}, this);
// Automatically re-render whenever the Collection is populated.
this.collection.on("reset", this.render, this);
}
});
// Patch Model and Collection.
_.each(["Model", "Collection"], function(name) {
// Cache Backbone constructor.
var ctor = Backbone[name];
// Cache original fetch.
var fetch = ctor.prototype.fetch;
// Override the fetch method to emit a fetch event.
ctor.prototype.fetch = function() {
// Trigger the fetch event on the instance.
this.trigger("fetch", this);
// Pass through to original fetch.
return fetch.apply(this, arguments);
};
});
@emileber
Copy link
Copy Markdown

For future readers, there's now a request event which replaces the fetch event here. And there's a sync event which is triggered when a model or collection has been successfully synced with the server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment