Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. //Customise Backbone.sync to work with Titanium rather than jQuery
  2. Backbone.sync = (function() {
  3. var methodMap = {
  4. 'create': 'POST',
  5. 'read' : 'GET',
  6. 'update': 'PUT',
  7. 'delete': 'DELETE'
  8. };
  9.  
  10. var xhr = Ti.Network.createHTTPClient({ timeout: 5000 });
  11.  
  12. return function(method, model, options) {
  13.  
  14. var type = methodMap[method],
  15. params = _.extend({}, options);
  16.  
  17.  
  18. //==== Start standard Backbone.sync code ====
  19.  
  20. // Ensure that we have a URL
  21. if (!params.url) params.url = getUrl(model) || urlError();
  22.  
  23. // Ensure that we have the appropriate request data.
  24. if (!params.data && model && (method == 'create' || method == 'update')) {
  25. params.contentType = 'application/json';
  26. params.data = JSON.stringify(model.toJSON());
  27. }
  28.  
  29. // For older servers, emulate JSON by encoding the request into an HTML-form.
  30. if (Backbone.emulateJSON) {
  31. params.contentType = 'application/x-www-form-urlencoded';
  32. params.processData = true;
  33. params.data = params.data ? {model : params.data} : {};
  34. }
  35.  
  36. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  37. // And an `X-HTTP-Method-Override` header.
  38. if (Backbone.emulateHTTP) {
  39. if (type === 'PUT' || type === 'DELETE') {
  40. if (Backbone.emulateJSON) params.data._method = type;
  41. params.type = 'POST';
  42. params.beforeSend = function(xhr) {
  43. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  44. };
  45. }
  46. }
  47.  
  48. //==== End standard Backbone.sync code ====
  49.  
  50.  
  51. //Handle success
  52. xhr.onload = function() {
  53. params.success(JSON.parse(this.responseText));
  54. };
  55.  
  56. //Handle error
  57. xhr.onerror = params.error;
  58.  
  59. //Prepare the request
  60. xhr.open(type, params.url);
  61.  
  62. //Add request headers etc.
  63. xhr.setRequestHeader('Content-Type', params.contentType);
  64. if (params.beforeSend) params.beforeSend(xhr);
  65.  
  66. //Make the request
  67. xhr.send(params.data);
  68. };
  69. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement