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'
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With