Justin Alexander
Justin Alexander

Reputation: 2024

Backbone: special encoding during save

Note: I know this is wrong, but this is a technical requirement by the server team.

I have a User object that extends Backbone.Model. It receives it's data using normal, mostly good, JSON from the server.

HOWEVER there is a requirement when saving THE SAME INFORMATION to encode emails with url encoding.

When receiving the data it is possible to pre-process it with the Backbone.Model.parse method, is there an equivalent way to pre-process the data before sending it? (without overriding the sync method)

Upvotes: 0

Views: 852

Answers (1)

Steve Halford
Steve Halford

Reputation: 26

I overrode Backbone.sync to change the format of the data to form encoded. However, with this method saving attributes that are arrays becomes a problem.

There's probably a better way to override sync, but I added this code to around line 1180 of the backbone.js file.

//convert to form encoded
if (Backbone.sendFormEncoded) {
  if (type === 'PUT' || type === 'DELETE' || type === 'POST') {
    params.contentType = 'application/x-www-form-urlencoded';
    var kvps = [], regEx = /%20/g;      
    var obj = model.toJSON();
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        if(obj[key]) {
          kvps.push(encodeURIComponent(key).replace(regEx, "+") + "=" + encodeURIComponent(obj[key].toString()).replace(regEx, "+"));
        } else {
          kvps.push(encodeURIComponent(key).replace(regEx, "+") + "=" + encodeURIComponent(obj[key]));
        }
      }
    }
    params.data = kvps ? kvps.join('&') : {};
  }
}

Be sure to set Backbone.sendFormEncoded to true for this block of code to run.

Upvotes: 1

Related Questions