Skip to content

Instantly share code, notes, and snippets.

@denisos
Created September 27, 2011 17:00
Show Gist options
  • Save denisos/1245613 to your computer and use it in GitHub Desktop.
Save denisos/1245613 to your computer and use it in GitHub Desktop.
Backbone.js model calling jsonp
// backbone.js continues to impress, I needed to get data from a jsonp api
// I really wanted to do this the "right" backbone.js way and create a model and call fetch.
// But the default backbone synch is not jsonp
// Turns out you can override a synch on a per model basis (thanks stackoverflow)
// whats nice is backbone.js continue to work as expected with the override
// here's a snippet (some changes to protect our privacy). An improvement could be to create a jsonp model class which MyModel inherits
// the synch function is most important below, that's what tells backbone it's jsonp
MyModel = Backbone.Model.extend({
url: function() {
return '/yourJsonpUrlhere';
},
// override backbone synch to force a jsonp call
sync: function(method, model, options) {
// Default JSON-request options.
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: model.url(),
jsonp: "jsonpCallback", // the api requires the jsonp callback name to be this exact name
processData: false
}, options);
// Make the request.
return $.ajax(params);
},
parse: function(response) {
// parse can be invoked for fetch and save, in case of save it can be undefined so check before using
if (response) {
if (response.success ) {
// here you write code to parse the model data returned and return it as a js object
// of attributeName: attributeValue
return {name: response.name}; // just an example,
}
}
}
});
@cabhishek
Copy link

you can simply do this someCollection.fetch({ dataType: 'jsonp' });

@gstephens
Copy link

Thanks for these posts. I also found that mdigital's version worked for me but parse was never called in the code above.

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