Backbone.js Model: Different URLs for Creating and Saving

My model is as follows:

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

I configure my api to react differently in order to respond more to formats. This works great for retrieving an existing entry, but when it tries to create a new one, it explicitly tries to send a message to / list / undefined.json. Is there a way I can tell if the model is new and will be saved for the first time, or would it be better to think, maybe take a look at the body of the request to determine if it is text / json?

+4
source share
3 answers

Backbone.Model instances have an isNew() function. When this is true, it means that it was never saved on the server.

+5
source

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

So, you can check if this is so - if the ID attribute has not been set, the model will be new.

+3
source

Check if the model has an id . If he saves it, otherwise create it.

 url : function() { if (this.isNew()) { return "/list.json"; } else { return "/list/" + this.id + ".json"; } } 
+2
source

Source: https://habr.com/ru/post/1398120/


All Articles