Sha256: 10794f21385720f9df87418f571a5b023fc411f7e1a8be74fd92cef1f79b1c24

Contents?: true

Size: 1.66 KB

Versions: 7

Compression:

Stored size: 1.66 KB

Contents

(function() {
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'delete': 'DELETE',
    'read'  : 'GET'
  };
  
  var getUrl = function(object) {
    if (!(object && object.url)) return null;
    return _.isFunction(object.url) ? object.url() : object.url;
  };
  
  var urlError = function() {
    throw new Error("A 'url' property or function must be specified");
  };

  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default JSON-request options.
    var params = _.extend({
      type:         type,
      dataType:     'json',
      beforeSend: function( xhr ) {
        var token = $('meta[name="csrf-token"]').attr('content');
        if (token) xhr.setRequestHeader('X-CSRF-Token', token);

        model.trigger('sync:start');
      }
    }, options);

    if (!params.url) {
      params.url = getUrl(model) || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!params.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';

      var data = {}

      if(model.paramRoot) {
        data[model.paramRoot] = model.toJSON();
      } else {
        data = model.toJSON();
      }

      params.data = JSON.stringify(data)
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET') {
      params.processData = false;
    }

    // Trigger the sync end event
    var complete = options.complete;
    params.complete = function(jqXHR, textStatus) {
      model.trigger('sync:end');
      if (complete) complete(jqXHR, textStatus);
    };
    
    // Make the request.
    return $.ajax(params);
  }
  
}).call(this);

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
rails-backbone-0.7.2 vendor/assets/javascripts/backbone_rails_sync.js
rails-backbone-0.7.1 vendor/assets/javascripts/backbone_rails_sync.js
backbonify-0.1.0 lib/assets/javascripts/backbone_rails_sync.js
rails-backbone-0.7.0 vendor/assets/javascripts/backbone_rails_sync.js
rails-backbone-0.6.1 vendor/assets/javascripts/backbone_rails_sync.js
rails-backbone-0.6.0 vendor/assets/javascripts/backbone_rails_sync.js
rails-backbone-0.6.0.rc vendor/assets/javascripts/backbone_rails_sync.js