Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone using emulatejson without getting model as parameter

I have a model which is sort of an "Action" that happens when a user clicks a button, for setting and removing an event. The event itself is another model and another collection, so technically I could send this request to the API without it even being a model, since I can update the event list independently when it's changed. Anyway, that wouldn't fix my problem which is sending data to the server.

My main problem:

When I use emulateJSON = true to make sure the POST is sent as an application/x-www-form-urlencoded type, all my data is wrapped in a model parameter as such:

model:{    
"eventid":"3",
"eventuniqueid":"abasdfasfafd",
"type":"Birthday",
"name":"Add"}

What I want is to have each of those as form parameters, like this:

eventid:"3",
eventuniqueid:"abasdfasfafd",
type:"Birthday",
name:"Add"

Is that possible easily?

like image 815
plebksig Avatar asked Jan 17 '26 18:01

plebksig


1 Answers

Easily? No. You'd have to redefine the behavior of the Model#sync method (the function is defined at Backbone.sync). No parameter allows you to customize it.

You'd have to change that part:

// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
  params.contentType = 'application/x-www-form-urlencoded';
  params.data = params.data ? {model: params.data} : {};
}

By deleting the last line I'd say, params.data being defined just before:

if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  params.contentType = 'application/json';
  params.data = JSON.stringify(options.attrs || model.toJSON(options));
}

Edit:
In fact, by passing your data the way you like while saving, you should be fine (you'd have both your data and Backbone's model parameter).

myModel.save({}, {data: myModel.toJSON()});
like image 185
Loamhoof Avatar answered Jan 20 '26 10:01

Loamhoof