Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone - using a different field name for id

Tags:

backbone.js

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'

})

like image 296
Chin Avatar asked Nov 04 '11 09:11

Chin


1 Answers

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

like image 82
timDunham Avatar answered Sep 22 '22 03:09

timDunham