Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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,
- }
- }
- }
- });
Add Comment
Please, Sign In to add comment