Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js model: Different URLs for create versus save

My model looks like the following right now:

window.List = Backbone.Model.extend({
    title: null,
    idAttribute : '_id',
    url : function() {
      return "/list/" + this.id + ".json";
    }
});

I'm tweaking my api to respond differently to become more response to formats. This works great for fetching an existing record, but when it tries to create a new one it obviously attempts to post to '/list/undefined.json'. Is there a way I can tell if the model is new and is going to be saved for the first time, or would it be a better idea to perhaps look at the request body to determine if it's text/json?

like image 521
James Avatar asked Dec 27 '22 05:12

James


2 Answers

Your Backbone.Model instances have a function isNew(). When this is true, it means it has never been saved to the server.

like image 76
Paul Hoenecke Avatar answered Dec 29 '22 17:12

Paul Hoenecke


As you said yourself, the id is undefined if the model is new (shouldn't it be _id, though?).

So, you can check if that is the case - if the ID attribute has not been set, the model is fresh.

like image 28
Borealid Avatar answered Dec 29 '22 19:12

Borealid