0
votes

If you look in the Backbone.js docs, the description of isNew() is:

Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

But no matter what I do, isNew always returns true.

As you can see below, I've created a new model (it even has a cid), added it to a collection, run a fetch() on the collection, and despite all that, isNew still returns true for the model. The save function is hitting a RESTful API that I've got running and the record is being successfully saved to the DB.

a = new TodoModel({title: 'hi there'});

> s {cid: "c14", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}

a.save();

> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

b = new TodoCollection();

> s {length: 0, models: Array[0], _byId: Object, constructor: function, model: function…}

b.add(a);

> s {cid: "c14", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}

b.fetch();

> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

a.isNew();

> true

So, how do I get isNew to return false?

1
Are you returning a unique ID from the server? It is the ID that decides if something is 'new' by default. - loganfsmyth

1 Answers

0
votes

Add your own isNew to your model. Maybe you want cid to be the thing that makes it new, or perhaps you have your own flag you set to false when you save it. Here's what I have done in the past.

isNew: function () {
    return this.id > 0 ? false : true;
}