0

I am running this code in backbone which saves some data to the server,

GroupModalHeaderView.prototype.save = function(e) {
  var $collection, $this;
  if (e) {
    e.preventDefault();
  }

  $this = this;
  if (this.$("#group-name").val() !== "") {
    $collection = this.collection;
    if (this.model.isNew()) {
      console.log("MODEL IS NEW");
      this.collection.add(this.model);
    }
    return this.model.save({ name: this.$("#group-name").val()}, {
      async: false,
      wait: true,
      success: function() {
        //console.log($this, "THIS");
        console.log('Successfully saved!');
        this.contentView = new app.GroupModalContentView({
          model: $this.model,
          collection: $this.collection,
          parent: this
        });
        this.contentView.render();
        return $this.cancel();
      },

    });
  }
};

This works fine the first time I run it, however if I run it again straight after saving my first piece of data it does not save new data it merely updates the last saved data. So the first time I save it runs a POST request and the next time it runs a PUT request, why would this be?

I am not sure if you need this but here is my initialise function -

GroupModalHeaderView.prototype.initialize = function() {
  _.bindAll(this)
}
Udders
  • 67
  • 2
  • 9

2 Answers2

1

Your view has a model object attached to it. As I understand you fill some forms, put their data to model and save the model. But all the time you have single model object, and you only update it's data. If you want to create a new object after saving model just add a line:

this.model = new YourModelClass();

right after line console.log('Successfully saved!');

Artem Volkhin
  • 1,362
  • 8
  • 22
0

From the backbone documentation:

If the model isNew, the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

If you want to make a post request even if the model is new, just override the default save implementation and call Backbone.sync(method, model, [options]) with 'create' as the passed method.

Protostome
  • 5,569
  • 5
  • 30
  • 45