admin管理员组

文章数量:1327555

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 bee 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?

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 bee 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?

Share Improve this question asked Feb 23, 2012 at 20:54 JamesJames 6,50911 gold badges61 silver badges87 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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

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.

Check if the model has an id. If it does save it, otherwise create it.

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

本文标签: javascriptBackbonejs model Different URLs for create versus saveStack Overflow