Question

In my view's method below, my model gets synced with the server if I understand the create() method properly. However, the console.log of this.model.id still returns undefined and this.model.isNew() returns true. The POST shows an id in the return JSON object and the model object attributes show an id as well, so why are they not reflecting properly in the model? I need the id to be set when I create the new view.

submitForm: function( e ) {
  e.preventDefault();

  this.model.set( this.$( '.editForm' ).serializeObject() );

  if ( this.model.isNew() )   {
    collection.create( this.model );

    console.log( this.model, this.model.id, this.model.isNew() );

    new MyView({
      model: this.model
    }).render().appendNode();
  }   else   {
    this.model.save();
  }

  this.closeForm();
}
Was it helpful?

Solution

So Jacob, the problem here is just that before rendering your view, you need to wait the response from the server. Your this.model.id will be undefined because your model is new, that means that it was not saved in the server yet.

So, what you could do is to work with the success callback from the .create function. I believe that something like this would work for you.

if (this.model.isNew()) {
  collection.create({
    // or you can use this.model (if it is an object)
    attribute_x: 'val',
    attribute_y: 'val'
  }, success: function(response){
    // here your model with have an id
    console.log(response);
    new MyView({
      model: response.model // check your response
    }).render().appendNode();             
  });
} else {
  new MyView({
    model: this.model
  }).render().appendNode();
}

So, as you can see, in the success callback, we render the View. And if you console.log the response you'll see what your back-end responded to you in the creation of the model.

OTHER TIPS

If you want, you can use the { wait: true } option when invoking create(); that way, the model won't be added to the collection until after it's successfully saved.

Combining this with having the rest of your logic occur on the collection's add event should take you a long way, probably. If you need to be able to distinguish between newly create'd models and ones added to the collection later, you can add another option to the create call (something like newlySaved: true, and then check for options.newlySaved in the add event callback).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top