0x_Anakin
0x_Anakin

Reputation: 3269

Backbone model initialization

I'm studying backbone and I'm trying to initialize an object but I get an empty object as a result from console. What am I doing wrong ?

Month = Backbone.Model.extend({
    month:"a",
    values:[
        {label:"Total", value:0}, 
        {label:"Expenses", value:0},
        {label:"Profit", value:0}
    ]   
});
var x = new Month();
console.log(x.toJSON())

Upvotes: 2

Views: 297

Answers (4)

kol
kol

Reputation: 28728

When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.

Source

The defaults hash (or function) can be used to specify the default attributes for your model. When creating an instance of the model, any unspecified attributes will be set to their default value.

Source

Upvotes: 0

Lix
Lix

Reputation: 48006

What you will want to do is set the defaults for that model.

Month = Backbone.Model.extend({
  defaults:{
    month:"a", 
    values:[
        { total: { label:"Total", value:0 }}, 
        { expenses: { label:"Expenses", value:0 }}, 
        { profit: { label:"Profit", value:0 }}, 
    ]
  }
});

This will make sure that when the Month object is created, it will have in it's attributes those attributes that you have defined in the defaults object. (I've changed the data a little bit, but I think you get the idea from my example).

You can read more in the documentation: http://backbonejs.org/#Model-defaults

The defaults hash (or function) can be used to specify the default attributes for your model. When creating an instance of the model, any unspecified attributes will be set to their default value.

Upvotes: 1

Karolis
Karolis

Reputation: 2959

var Month = Backbone.Model.extend({
  // you put your Model's methods here or override existing Backbone Model methods here
});
var x = new Month({
  // you put the data of the model here
  month:"a",
  values:[
    {label:"Total", value:0}, 
    {label:"Expenses", value:0},
    {label:"Profit", value:0}
  ]
});
console.log(x.toJSON())

UPDATE One important point here is that the values array is going to be shared among all instances of this model, because it's being initialized at the file execution time and being references by the value attribute. So if you have 2 models and say change the Expenses value in the array in model 1, the Expenses in model 2 will also be updated. Something like https://github.com/powmedia/backbone-deep-model could help deal with deeply nested data.

Upvotes: 0

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

A Backbone.Model is a single object, you can't initialize it with an array.

But you can initialize it with a single object like this :

Month = Backbone.Model.extend({
    defaults: {label:"Total", month:"a", value:0}   
});
var x = new Month();
console.log(x.toJSON())

Upvotes: 3

Related Questions