There is no magic behind backbone.js model.isNew()

model.isNew() can be quite useful, this method can be interesting when handling and changing forms behaviors from adding new items, to updating and deleting them. At first I did not quite understand how isNew() was working internally and, one day it just stopped working and that was frustrating!

It’s all about the id

One thing I like to do is prepopulate my fields with defaults values. Backbone has a great feature for that, when instantiating a model you can pass a defaults object.

var Meal = Backbone.Model.extend({
  defaults: {
    "appetizer":  "caesar salad",
    "entree":     "ravioli",
    "dessert":    "cheesecake"
  }
});

Thing is, for some (stupid) reasons I was sometimes also passing an empty id, and there was my problem! In my head I was sure that somewhere in the model objet there was a state knowing if it was new or not, but backbone.js rely entirely on the id.

So there you go, if model.isNew() return false and you have no idea why, check if your model has an id, chances are, this is your problem.

Cedric Dugas is an experienced front-end developer and founder of Position: Absolute, based in Montreal, Canada. When he is not doing CSS and jquery (does it ever happen?), he likes to read on web usability and play trumpet. Why don't you follow him on twitter.

Got something to say? Go for it!