Skip to content

Instantly share code, notes, and snippets.

@jackwanders
Last active December 31, 2015 23:49
Show Gist options
  • Save jackwanders/8062338 to your computer and use it in GitHub Desktop.
Save jackwanders/8062338 to your computer and use it in GitHub Desktop.
Backbone Collection with a built-in fetch promise
/*global define*/
/**
* Backbone.Promise - You'll tell me when you're ready, won't you?
*
* Let's create a collection that immediately fetches itself upon
* instantiation, and provide a promise for the completion of said fetch.
*
* Why? Because why not?
*
*/
define([
'jquery',
'backbone'
], function ($, Backbone) {
'use strict';
Backbone.Promise = {};
var oldCollection = Backbone.Collection;
/**
* Backbone.Promise.Collection
* An extension of Backbone.Collection that does two things:
* 1) Create a promise for hooking into fetch completion
* 2) Immediately fetch collection on creation
*
* Admittedly, #2 is a fairly opinionated way of doing business
*/
Backbone.Promise.Collection = Backbone.Collection.extend({
constructor: function() {
var deferred = new $.Deferred();
this.dataFetch = deferred.promise();
// convenience method for calling .done on our promise
this.afterFetch = function(callback) {
this.dataFetch.done(callback);
};
oldCollection.apply(this, arguments);
// immediately fetch our collection when it's created
this.fetch({
success: function() { deferred.resolve(); },
error: function() { deferred.reject(); }
});
}
});
// override deafult collection
Backbone.Collection = Backbone.Promise.Collection;
// provide a no-conflict option
Backbone.Promise.Collection.noConflict = function() {
Backbone.Collection = oldCollection;
};
return {
noConflict: function() {
Backbone.Promise.Collection.noConflict();
}
};
});
@idris
Copy link

idris commented Dec 20, 2013

On line 45-46, I think success and error get a jqXHR passed to them, so you could pass that along (not to mention error states, etc). You may even be able to do some promise piping magic.

@jackwanders
Copy link
Author

i like the way you think

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