Last active
December 31, 2015 23:49
-
-
Save jackwanders/8062338 to your computer and use it in GitHub Desktop.
Backbone Collection with a built-in fetch promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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(); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On line 45-46, I think
success
anderror
get ajqXHR
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.