Skip to content

Instantly share code, notes, and snippets.

@m-coding
Forked from michielvaneerd/Backbone and JSONP
Created March 25, 2016 07:50
Show Gist options
  • Save m-coding/4ea2403abeae3f37adbe to your computer and use it in GitHub Desktop.
Save m-coding/4ea2403abeae3f37adbe 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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment