1

In this particular case I hard-coded in the method to create or POST and also set both the emulate options to false. After applying this logic I got this much shorter method:

  // hard code in the emulation and method
  Backbone.sync = function(method, model, options) {
    options || (options = {});
    var params = {type: 'POST', dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }
    params.processData = false;

    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };
  • removing the emulation values does not change anything as they are already hard-coded to `false` any ways. my server is setup for handling `JSON POST` and I don't have time for writing server side code at the moment and I need a quick solution to get things up and running –  Jul 29 '14 at 12:28

1 Answers1

1

Generally, the accepted answer for hardcoding is do it in such a way that makes your method reusable. You're essentially trying to make less work for yourself down the road.

In this case, sections like having POST and JSON are fine. Do you see yourself planning to change the method from a POST to a GET? Do you plan on writing a GET method? Then make it a parameter, or a configurable option. (I highly doubt in your case, but I'm just using that as an example)

In terms of getting data and all that, you seem to be ok as testing. (since you just wanna get your feet off the ground). Just remember to add in the method switch statement for each of the different data cases...

Edit: The method switch is creating a switch statement on the first parameter, which defines what kind of operation is being done on the data. Here is an example:

Backbone.sync = function(method, model, options) {
    options || (options = {});
    var params = {type: 'POST', dataType: 'json'};
    switch (method) {
       case 'create':           
       //Let's go make data (POST)
       ...
       break;

       case 'update':
       //let's go update our data
       ...
       break;

       case 'delete':
       //Let's remove some data
       ...
       break;

       case 'read':
       //let's go gather our data (GET)
       ...
       break;
   }
   return xhr;
};
Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36