Last active
November 4, 2021 16:27
Fetching a Backbone collection with JSONP is really simple. It turns out you only need to override the sync method (to set the dataType to jsonp). In this case I also had to override the parse method, because the response consists of more than the models. This example uses the Discogs API to search for artists.
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
var Artist = Backbone.Model.extend(); | |
var Artists = Backbone.Collection.extend({ | |
model : Artist, | |
url : "http://api.discogs.com/database/search?type=artist", | |
sync : function(method, collection, options) { | |
// By setting the dataType to "jsonp", jQuery creates a function | |
// and adds it as a callback parameter to the request, e.g.: | |
// [url]&callback=jQuery19104472605645155031_1373700330157&q=bananarama | |
// If you want another name for the callback, also specify the | |
// jsonpCallback option. | |
// After this function is called (by the JSONP response), the script tag | |
// is removed and the parse method is called, just as it would be | |
// when AJAX was used. | |
options.dataType = "jsonp"; | |
return Backbone.sync(method, collection, options); | |
}, | |
parse : function(response) { | |
return response.data.results; | |
} | |
}); | |
var artists = new Artists(); | |
artists.fetch({ | |
data : { | |
q : "bananarama" | |
}, | |
success : function(collection, response, options) { | |
console.log(collection); | |
console.log(response); | |
console.log(options); | |
}, | |
error : function(collection, response, options) { | |
console.log(response.statusText); | |
}, | |
// A timeout is the only way to get an error event for JSONP calls! | |
timeout : 5000 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bweston92
By the end of the
sync
method, there's this:_.extend(params, options)
mergesoptions
(our newdataType
) with the defaultsparams
.options
values overwrite anyparams
that are equal.