Guest User

Untitled

a guest
Jan 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. // backbone.js continues to impress, I needed to get data from a jsonp api
  2. // I really wanted to do this the "right" backbone.js way and create a model and call fetch.
  3. // But the default backbone synch is not jsonp
  4. // Turns out you can override a synch on a per model basis (thanks stackoverflow)
  5. // whats nice is backbone.js continue to work as expected with the override
  6.  
  7. // here's a snippet (some changes to protect our privacy). An improvement could be to create a jsonp model class which MyModel inherits
  8. // the synch function is most important below, that's what tells backbone it's jsonp
  9.  
  10. MyModel = Backbone.Model.extend({
  11. url: function() {
  12. return '/yourJsonpUrlhere';
  13. },
  14.  
  15. // override backbone synch to force a jsonp call
  16. sync: function(method, model, options) {
  17. // Default JSON-request options.
  18. var params = _.extend({
  19. type: 'GET',
  20. dataType: 'jsonp',
  21. url: model.url(),
  22. jsonp: "jsonpCallback", // the api requires the jsonp callback name to be this exact name
  23. processData: false
  24. }, options);
  25.  
  26. // Make the request.
  27. return $.ajax(params);
  28. },
  29.  
  30. parse: function(response) {
  31. // parse can be invoked for fetch and save, in case of save it can be undefined so check before using
  32. if (response) {
  33. if (response.success ) {
  34. // here you write code to parse the model data returned and return it as a js object
  35. // of attributeName: attributeValue
  36.  
  37. return {name: response.name}; // just an example,
  38. }
  39. }
  40. }
  41. });
Add Comment
Please, Sign In to add comment