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) ); },
source share