Backbone.sync to overwrite dataType

I am creating an application that uses a .CSV file as a data source for the Backbone model. What would be the best approach to rewrite synchronization to use dataType "text" rather than "json"? Search for best practices, etc.

Unfortunately, the "dataType" parameter used by Backbone.sync is hard-coded ... and does not respond to options.dataType. The piece of code in question can be seen in the annotated source - http://backbonejs.org/docs/backbone.html#section-166

This is the synchronization method that I created on my model. Most of them copy paste directly from Backbone.sync. My model is also read-only.

sync: function(method, model, options){ //overwrite sync to read a .CSV document. if //the default Backbone sync would let you //specify the "dataType" property, this wouldn't //be necessary. if(method === 'read'){ options || (options = {}); var success = options.success; options.success = function(resp, status, xhr) { if (success) success(json, status, xhr); }; var params = {type: 'GET', dataType: 'text', url: this.url}; return $.ajax(_.extend(params, options)); } }, 

I rewrote the parsing to handle the CSV response.

 parse: function(data, xhr){ return $jQuery.parseJSON( CSVParser.toJSON(data) ); }, 
+4
source share
1 answer

Instead of changing the main trunk or copying the entire synchronization method just to change the data type, you can use one of jQuery's not-so-well-known functions called ajaxPrefilter .

Witch allows you to modify an ajax request just before creating it. I really need a function.

 jQuery.ajaxPrefilter(function( options ) { options.dataType = "mynewdatatype"; }); 

Not sure if this works with zepto.js.

+1
source

All Articles