Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mdigital/2886126 to your computer and use it in GitHub Desktop.
Save mdigital/2886126 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()+"?callback=?",
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,
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment