30

I'm porting an old app to use backbone.js (hopefully) Problem is none of the various objects in the system use 'id' for id - each object is different. Reading around, I've come up with the solution below when initializing the Backbone.Model.

   initialize: function(){
    this.idAttribute = 'user_ID';
    this.set({'id':this.get('user_ID')});
 }

I'm worried however that as I develop with backbone this approach is gonna bite me. Does anyone have any experience with this. Any pointers much appreciated.

edit: I just called isNew() on the model and got true, even though the id is now set to 1. ///////////////////////////////////////////

Using the following seems to sort it out.

User = Backbone.Model.extend({
idAttribute : 'user_ID'

})

Chin
  • 12,582
  • 38
  • 102
  • 152

1 Answers1

49

When you use idAttribute, backbone basically keeps the id property in sync with the user_ID property. The way it's normally used is when you define your class

var UserModel = Backbone.Model.extend({
    idAttribute: 'user_ID',
    initialize: function() {
        //do stuff
    }
});

var me = new UserModel({user_ID: 1234, name: 'Tim'});
console.log(me.id); //1234
console.log(me.get('user_ID')); //1234
console.log(me.isNew()); //false

var me2 = new UserModel({name: 'newUser'});
console.log(me2.isNew()); //true

Good Luck

timDunham
  • 3,318
  • 23
  • 24
  • 2
    Just stumbled upon this when I asked myself the question If should use id-suffixes like "id_user" instead of "id" in my relational database schema for a backbone project. I got convinced that it's better to use them according to [this](http://stackoverflow.com/a/1369773/2236166) , then I thought "Doh, but the id fields for backbone models...", until I read this Q&A. Thanks! – morten.c Mar 22 '14 at 01:34
  • 1
    A little obvious but don't use .get('id') unless you want the original id value (if you have one). Always use 'model.id'. – backdesk Apr 01 '15 at 11:17