I'm having a problem saving an existing model after a form submit in my backbone/marionette app.
So, I submit the form and use backbone.syphon to create a representation of the form data. The object I build looks like this :
{languages: {
{
de_DE: {
default: false
enabled: true
},
en_US: {
...
}
...
}
}
I'm trying to save it to a backbone model with attributes that looks like this:
attributes: {
id: "5"
languages: {
de_DE: {
default: false,
label: "German"
language: "de_DE"
selected: false
},
en_CA: {
...
},
...
}
}
The problem is that when I save the existing model using model.save(data)
using the above data structure for my data, the default and label instances are completely removed from my model. They're not even sent to the server. They are just completelely removed, though they do sit in the previousAttrs
object.
The instance of my model's sync setup looks so:
sync: function(method, model, options){
var baseUrl = window.location.origin+'/qp-api/v1/master-app/';
var config = {}
switch(method){
case "create":
break;
case "read":
config = _.extend(config, {
method: "GET",
url: baseUrl+this.id+'/languages'
});
break;
case "update":
config =_.extend({
method: "PUT",
url: baseUrl+this.id+'/languages'
});
break;
case "delete":
break;
};
options = _.extend(options, config);
return Backbone.Model.prototype.sync.call(this, method, model, options);
},
What am I doing wrong? I thought backbone's save function would only update the changed attrs. It looks to me like my data object should map to the setup of my models attrs. Shouldn't they just update? Am I not understanding something about how existing model's save?
At first I want to mention that it's not a good idea to make such checks
if(languages.save(data){ .... })
.model.save()
will return promise object, so yourif
condition will not work as expected.One of the solutions for your issue is to override languages model's
save
method.Hope this helps!