I’ve got my models saving and updating using the regular save with a success callback.
But I’m trying to figure out how to define a separate add view depending on if the model is new, or an update to an already existing model.
This is not server side. I have the server create/update working fine, I’m trying to figure out what is the ‘right’ way to update the view.
My code is pretty straight forward
Myapp.FormInput = Backbone.Views.extend({
initialize: function(){...
},
submit_form: function(){
if(this.id===undefined){
// this is a new model, so create it
model.set(new Myapp.Model.set(Myapp.Models.Helpers.serialize_objects(form)));
model.set({parent_id:parent.id});
} else {
// this is an update to an existing model, so just update the model
model.set(Myapp.Model.set(Myapp.Models.Helpers.serialize_objects(form)));
model.url+='/'+this.id;
}
model.save(model,
{success: function(model){
Myapp.Collection.add(model);
}, error: function(){
alert('error creating or updating');
}}
});
});
What I like to do is initialize the ‘View’ from the router with a ‘Model’, if I am editing, and without a ‘Model’, if I am creating a new ‘Model’ from scratch.
The idea would be :
And then, in the ‘render’ method, check for a model in this view instance.
But.. this only works if your application use different routes for editing and creating models. Maybe you are doing everything in the same route in a most elaborate way (or you have other reasons).
You could try something like this:
Define your
model.save‘success’ function in the View (that is, in the same way that you define your submit_form in your example) and add a code line where you associate the model to this view:In order this to work, you have to bind the view to your new success function (this is the reason you define it outside).
You could make it in the view initialize function like this (more information about ‘_bind’ here):
Now, in your ‘render’ method you can render the form and, after that, check if ‘
this.model‘ is ‘undefined’, if it is not, you know now that you have to fill the content.Disclaimer: I have not checked the code, so probably a copy paste is not going to work but hopefully you can get the idea.