Skip to content

Instantly share code, notes, and snippets.

@michielvaneerd
Last active November 4, 2021 16:27
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save michielvaneerd/5989839 to your computer and use it in GitHub Desktop.
Save michielvaneerd/5989839 to your computer and use it in GitHub Desktop.
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.
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
});
@dudelorf
Copy link

This was very helpful, thank you

@bweston92
Copy link

How can you overwrite dataType it is hard-coded with no way of over-writing?
https://github.com/jashkenas/backbone/blob/master/backbone.js#L1394

@RaphaelDDL
Copy link

RaphaelDDL commented Aug 24, 2016

@bweston92

By the end of the sync method, there's this:

var xhr = options.xhr = Backbone.ajax(_.extend(params, options));

_.extend(params, options) merges options (our new dataType) with the defaults params. options values overwrite any params that are equal.

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