Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: Id not being set to model

I have tried the following to set an id to my model:

var globalCounter = 1;

var Model = Backbone.Model.extend({
    initialize: function () {
        this.id = globalCounter;
        globalCounter += 1;
    }
});

myModel = new Model();
console.log(myMode.get('id')); // prints undefined

How can I set an id to my models?

like image 358
Randomblue Avatar asked Sep 24 '12 22:09

Randomblue


1 Answers

You need to use the set() function instead (http://jsbin.com/agosub/1/);

var globalCounter = 1;

var Model = Backbone.Model.extend({
    initialize: function () {
        this.set('id', globalCounter);
        globalCounter += 1;
    }
});

myModel = new Model();
console.log(myModel.get('id')); // prints 1
like image 193
Matt Avatar answered Oct 08 '22 21:10

Matt