3

I have a very basic backbone (sample) application which just creates and destroys model items. When the model is created the object is persisted with a POST to the web server, but when the model is destroyed there is no DELETE sent to the server? Any idea why this might be?

very basic model:

window.User = Backbone.Model.extend({
  urlRoot: 'users'
});

my test code just to create and delete the model:

var model = null;

$(".add").click(function(){
  if (model == null) {
    model = new window.User;
    model.set({name: 'meeee'});
    model.save();
  }
});

$(".remove").click(function(){
  if (model != null) {
    model.destroy();
  }
});

The JSON response when creating the model seems good too:

enter image description here

Nippysaurus
  • 20,110
  • 21
  • 77
  • 129
  • 3
    how does your server respond to the `save` request? If the model doesn't have an `.id` attribute (Which the server is supposed to return when saving), it won't send any request. – Esailija Jun 03 '12 at 21:53
  • updated the question with screenshot of json response. – Nippysaurus Jun 03 '12 at 22:27

1 Answers1

12

Backbone doesn't know that _id is the name you are using for your id field, unless you've modified your copy of Backbone.js somehow (please don't). To tell Backbone what the name of your id field is for some particular model, idAttribute in your Model definition. Otherwise, it defaults to the regular id.

Without the "identity" field set, Backbone is going to consider that the the model instance "isNew" (a model instance which hasn't been persisted to the server), so when there's no "identity" (as in your case, as it doesn't know that your identity is, instead, _id) there wouldn't be any need to destroy it on the server.

JayC
  • 7,053
  • 2
  • 25
  • 41
  • I feel a little embarrassed that I didn't notice the underscore ... That is almost certainly the issue. Had a little chuckle at your "please don't" :-) – Nippysaurus Jun 03 '12 at 23:44
  • `POST` instead of `DELETE` when `destroy()` is called? Back then this was probably caused by [`Backbone.emulateHTTP`](https://github.com/jashkenas/backbone/blob/0.9.2/backbone.js#L1343) being `true`. Related: https://stackoverflow.com/questions/52069982/backbone-destroy-method-is-triggering-post-call-instead-of-delete-when-type-de – try-catch-finally Aug 29 '18 at 07:53